当前位置:   article > 正文

C++ STL——栈和队列(stack & queue)_c++ stl stack

c++ stl stack

本节目标

1.stack的介绍和使用及其模拟实现

2.queue的介绍和使用及其模拟实现

3.priority_queue的介绍和使用及其模拟实现

4.容器适配器

1.stack的介绍和使用及其模拟实现

1.1 stack的介绍

stack的文档介绍

根据stack的文档介绍可以知道,stack是一种容器适配器,专门设计用于在后进先出上下文(后进先出)中运行,其中元素仅从容器的一端插入和提取。

stack作为容器适配器实现,容器适配器是使用特定容器类的封装对象作为其底层容器的类,提供一组特定的成员函数来访问其元素。元素从特定容器的“背面”推出/弹出,这被称为stack的顶部(即栈顶)

stack的底层容器可以是任何标准容器类模板,也可以是一些其他专门设计的容器类。容器应支持以下操作:

  • empty
  • back
  • push_back
  • pop_back

标准容器类 vector、deque、    list ,均满足这些要求。默认情况下,如果未为特定类实例化指定容器类,则使用标准容器deque作为底层容器。

1.2 stack的使用

以上是stack的成员函数,用蓝色框框框起来的几个成员函数接口是需要重点掌握的

简单说明:

1.stack()是构造一个空的stack

2.empty()是用于判断stack是否为空

3.size()是用来返回stack中元素的个数

4.top()适用于返回栈顶元素的引用

5.push()将元素压入stack中

6.pop()将stack中尾部的元素弹出

下面对这几个接口进行使用,以下是简单的测试代码:

  1. #include<iostream>
  2. #include<stack>
  3. #include<queue>
  4. using namespace std;
  5. void test_stack1()
  6. {
  7. stack<int> st;
  8. st.push(1);
  9. st.push(2);
  10. st.push(3);
  11. st.push(4);
  12. while (!st.empty())
  13. {
  14. cout << st.top() <<" ";
  15. st.pop();
  16. }
  17. }
  18. int main()
  19. {
  20. test_stack1();
  21. return 0;
  22. }

运行结果如下:

当然也不一定是入1,2,3,4出的序列就一定是4,3,2,1。也可以边入边出

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include<iostream>
  3. #include<stack>
  4. #include<queue>
  5. using namespace std;
  6. void test_stack1()
  7. {
  8. stack<int> st;
  9. st.push(1);
  10. st.push(2);
  11. cout << st.top() << " ";
  12. st.pop();
  13. st.push(3);
  14. st.push(4);
  15. while (!st.empty())
  16. {
  17. cout << st.top() <<" ";
  18. st.pop();
  19. }
  20. }
  21. int main()
  22. {
  23. test_stack1();
  24. return 0;
  25. }

运行结果如下:

学会了如何使用之后我们可以对该oj题进行挑战

用两个栈实现队列

OJ题参考:

  1. class MyQueue {
  2. public:
  3. MyQueue() {
  4. }
  5. void push(int x) {
  6. st1.push(x);
  7. }
  8. int pop() {
  9. if(st2.empty())
  10. {
  11. while(!st1.empty())
  12. {
  13. st2.push(st1.top());
  14. st1.pop();
  15. }
  16. }
  17. int top = st2.top();
  18. st2.pop();
  19. return top;
  20. }
  21. int peek() {
  22. if(st2.empty())
  23. {
  24. while(!st1.empty())
  25. {
  26. st2.push(st1.top());
  27. st1.pop();
  28. }
  29. }
  30. return st2.top();
  31. }
  32. bool empty() {
  33. return st1.empty()&&st2.empty();
  34. }
  35. private:
  36. stack<int> st1;//用来实现从队尾入队列
  37. stack<int> st2;//用来实现从队头出队列
  38. };

最小栈

参考实现:

思路是用两个栈来实现,一个用来放栈中的数据,一个用来存放该栈数据中的最小值,如果初始时st为空,那么push的就是目前栈中的最小值,然后把这个最小值在Minst这个栈中push进去,如果st中push的值小于Minst目前的最小值则要继续push,如果与最小值相等,为了pop之后不受影响,则也要在Minst中继续push该相等的最小值,这样就能实现一直能够获取栈中的最小值了。

  1. class MinStack {
  2. public:
  3. MinStack() {
  4. }
  5. void push(int val) {
  6. if(st.empty()||Minst.top()>=val)
  7. {
  8. Minst.push(val);
  9. }
  10. st.push(val);
  11. }
  12. void pop() {
  13. if(st.top()==Minst.top())
  14. {
  15. Minst.pop();
  16. }
  17. st.pop();
  18. }
  19. int top() {
  20. return st.top();
  21. }
  22. int getMin() {
  23. return Minst.top();
  24. }
  25. stack<int> st;
  26. stack<int> Minst;
  27. };

栈的压入弹出序列

解题思路:

代码参考实现:

  1. class Solution {
  2. public:
  3. /**
  4. * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
  5. *
  6. *
  7. * @param pushV int整型vector
  8. * @param popV int整型vector
  9. * @return bool布尔型
  10. */
  11. bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {
  12. // write code here
  13. stack<int> st;
  14. int pushi= 0,popi = 0;
  15. while(pushi<pushV.size())
  16. {
  17. st.push(pushV[pushi]);
  18. while(!st.empty()&&st.top()==popV[popi])
  19. {
  20. st.pop();
  21. popi++;
  22. }
  23. pushi++;
  24. }
  25. return st.empty();
  26. }
  27. };

1.3stack的模拟实现

  1. #include<deque>
  2. namespace mystack
  3. {
  4. template<class T, class Container=deque<T>>
  5. class stack
  6. {
  7. public:
  8. void push(const T& x)
  9. {
  10. _con.push_back(x);
  11. }
  12. void pop()
  13. {
  14. _con.pop_back();
  15. }
  16. const T& top()
  17. {
  18. return _con.back();
  19. }
  20. size_t size()
  21. {
  22. return _con.size();
  23. }
  24. bool empty()
  25. {
  26. return _con.empty();
  27. }
  28. private:
  29. Container _con;
  30. };
  31. }

模拟实现功能测试代码:

  1. void test_stack2()
  2. {
  3. mystack::stack<int> st;
  4. st.push(1);
  5. st.push(2);
  6. st.push(3);
  7. st.push(4);
  8. while (!st.empty())
  9. {
  10. cout << st.top() << " ";
  11. st.pop();
  12. }
  13. }

运行结果截图:

2.queue的介绍和使用及其模拟实现

2.1 queue的介绍

queue的文档介绍

根据queue的文档介绍可以知道,

队列 是一种容器适配器,专门设计用于在 FIFO 上下文(先进先出)中运行,其中元素插入容器的一端并从另一端提取。

队列作为容器适配器实现,容器适配器是使用特定容器类的封装对象作为其基础容器的类,提供一组特定的成员函数来访问其元素。元素被推入特定容器的“背面”(即队尾),并从其“正面”(即队头)弹出
基础容器可以是标准容器类模板之一,也可以是其他一些专门设计的容器类。此基础容器应至少支持以下操作:

  • empty
  • size
  • front
  • back
  • push_back
  • pop_front


标准容器类,并满足这些要求。默认情况下,如果未为特定类实例化指定容器类,则使用标准容器。deque   list   queue     deque

2.2 queue的使用

以上是queue的成员函数接口,下面对这几个接口进行简单介绍:

1.queue()是构造一个空的queue

2.empty()是用于判断queue是否为空,是的话返回true,否则返回false.

3.size()是用来返回queue中元素的个数

4.top()适用于返回队头元素的引用

5.push()在队尾将元素入队列

6.pop()将队头元素出队列

下面我们对这些成员函数接口进行使用

  1. #include<iostream>
  2. #include<queue>
  3. using namespace std;
  4. void test_queue1()
  5. {
  6. queue<int> q;
  7. q.push(1);
  8. q.push(2);
  9. q.push(3);
  10. q.push(4);
  11. while (!q.empty())
  12. {
  13. cout << q.front() << " ";
  14. q.pop();
  15. }
  16. }
  17. int main()
  18. {
  19. test_queue1();
  20. return 0;
  21. }

运行结果如下:

熟悉了这些使用之后我们可以挑战一些该oj题目:

用队列实现栈

2.3 queue的模拟实现

  1. namespace myqueue
  2. {
  3. template<class T,class Container=deque<T>>
  4. class queue
  5. {
  6. public:
  7. void push(const T& x)
  8. {
  9. _con.push_back(x);
  10. }
  11. void pop()
  12. {
  13. _con.pop_front();
  14. }
  15. const T& front()
  16. {
  17. return _con.front();
  18. }
  19. const T& back()
  20. {
  21. return _con.back();
  22. }
  23. size_t size()
  24. {
  25. return _con.size();
  26. }
  27. bool empty()
  28. {
  29. return _con.empty();
  30. }
  31. private:
  32. Container _con;
  33. };
  34. }

代码测试:

  1. void test_queue2()
  2. {
  3. myqueue::queue<int> q;
  4. q.push(4);
  5. q.push(3);
  6. q.push(1);
  7. q.push(0);
  8. q.push(2);
  9. q.push(5);
  10. while (!q.empty())
  11. {
  12. cout << q.front() << " ";
  13. q.pop();
  14. }
  15. cout << endl;
  16. }

运行结果:

3. priority_queue的介绍和使用及其模拟实现

3.1 priority_queue的介绍

priority_queue的文档介绍

1. 优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
2. 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元
素)。
3. 优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特
定的成员函数来访问其元素。元素从特定容器的“尾部”弹出,其称为优先队列的顶部。
4. 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭
代器访问,并支持以下操作:
empty():检测容器是否为空
size():返回容器中有效元素个数
front():返回容器中第一个元素的引用
push_back():在容器尾部插入元素

pop_back(): 删除容器尾部元素
5. 标准容器类vector和deque满足这些需求。默认情况下,如果没有为特定的priority_queue类实例化指
定容器类,则使用vector。
6. 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数
make_heap、push_heap和pop_heap来自动完成此操作。

3.2 priority_queue的使用

以上是priority_queue的成员函数接口,下面对常用的接口进行简单说明


priority_queue()/priority_queue(first,last)   构造一个空的优先级队列
empty( )      检测优先级队列是否为空,是返回true,否则返回false
top( )    返回优先级队列中最大(最小元素),即堆顶元素
push(x)   在优先级队列中插入元素x
pop()   删除优先级队列中最大(最小)元素,即堆顶元素

  1. void test_mypriority_queue()
  2. {
  3. mypriority_queue::priority_queue<int> pq;
  4. pq.push(4);
  5. pq.push(3);
  6. pq.push(1);
  7. pq.push(0);
  8. pq.push(2);
  9. pq.push(5);
  10. while (!pq.empty())
  11. {
  12. cout << pq.top() << " ";
  13. pq.pop();
  14. }
  15. cout << endl;
  16. }

运行结果如下:

在OJ中的使用:

数组中第K个大的元素

3.3 priority_queue的模拟实现

  1. #pragma once
  2. #include <iostream>
  3. using namespace std;
  4. #include <vector>
  5. // priority_queue--->堆
  6. namespace mypriority_queue
  7. {
  8. template<class T>
  9. struct less
  10. {
  11. bool operator()(const T& left, const T& right)
  12. {
  13. return left < right;
  14. }
  15. };
  16. template<class T>
  17. struct greater
  18. {
  19. bool operator()(const T& left, const T& right)
  20. {
  21. return left > right;
  22. }
  23. };
  24. template<class T, class Container = std::vector<T>, class Compare = less<T>>
  25. class priority_queue
  26. {
  27. public:
  28. // 创造空的优先级队列
  29. priority_queue() : c() {}
  30. template<class Iterator>
  31. priority_queue(Iterator first, Iterator last)
  32. : c(first, last)
  33. {
  34. // 将c中的元素调整成堆的结构
  35. int count = c.size();
  36. int root = ((count - 2) >> 1);
  37. for (; root >= 0; root--)
  38. AdjustDown(root);
  39. }
  40. void push(const T& data)
  41. {
  42. c.push_back(data);
  43. AdjustUP(c.size() - 1);
  44. }
  45. void pop()
  46. {
  47. if (empty())
  48. return;
  49. swap(c.front(), c.back());
  50. c.pop_back();
  51. AdjustDown(0);
  52. }
  53. size_t size()const
  54. {
  55. return c.size();
  56. }
  57. bool empty()const
  58. {
  59. return c.empty();
  60. }
  61. // 堆顶元素不允许修改,因为:堆顶元素修改可以会破坏堆的特性
  62. const T& top()const
  63. {
  64. return c.front();
  65. }
  66. private:
  67. // 向上调整
  68. void AdjustUP(int child)
  69. {
  70. int parent = ((child - 1) >> 1);
  71. while (child)
  72. {
  73. if (Compare()(c[parent], c[child]))
  74. {
  75. swap(c[child], c[parent]);
  76. child = parent;
  77. parent = ((child - 1) >> 1);
  78. }
  79. else
  80. {
  81. return;
  82. }
  83. }
  84. }
  85. // 向下调整
  86. void AdjustDown(int parent)
  87. {
  88. size_t child = parent * 2 + 1;
  89. while (child < c.size())
  90. {
  91. // 找以parent为根的较大的孩子
  92. if (child + 1 < c.size() && Compare()(c[child], c[child + 1]))
  93. child += 1;
  94. // 检测双亲是否满足情况
  95. if (Compare()(c[parent], c[child]))
  96. {
  97. swap(c[child], c[parent]);
  98. parent = child;
  99. child = parent * 2 + 1;
  100. }
  101. else
  102. return;
  103. }
  104. }
  105. private:
  106. Container c;
  107. };
  108. }
  109. void TestQueuePriority()
  110. {
  111. mypriority_queue::priority_queue<int> q1;
  112. q1.push(5);
  113. q1.push(1);
  114. q1.push(4);
  115. q1.push(2);
  116. q1.push(3);
  117. q1.push(6);
  118. cout << q1.top() << endl;
  119. q1.pop();
  120. q1.pop();
  121. cout << q1.top() << endl;
  122. vector<int> v{ 5,1,4,2,3,6 };
  123. mypriority_queue::priority_queue<int, vector<int>, mypriority_queue::greater<int>> q2(v.begin(), v.end());
  124. cout << q2.top() << endl;
  125. q2.pop();
  126. q2.pop();
  127. cout << q2.top() << endl;
  128. }

4.容器适配器

4.1什么是容器适配器?

适配器是一种设计模式(设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结),该种模式是将一个类的接口转换成客户希望的另外一个接口。

4.2 STL标准库中stack和queue的底层结构

虽然stack和queue中也可以存放元素,但在STL中并没有将其划分在容器的行列,而是将其称为容器适配器,这是因为stack和队列只是对其他容器的接口进行了包装,STL中stack和queue默认使用deque,比如:

4.3deque的简单介绍

deque(双端队列):是一种双开口的"连续"空间的数据结构,双开口的含义是:可以在头尾两端进行插入和删除操作,且时间复杂度为O(1),与vector比较,头插效率高,不需要搬移元素;与list比较,空间利用率比较高。

deque并不是真正连续的空间,而是由一段段连续的小空间拼接而成的,实际deque类似于一个动态的二维数组。

双端队列底层是一段假象的连续空间,实际是分段连续的,为了维护其“整体连续”以及随机访问的假象,落在了deque的迭代器身上,因此deque的迭代器设计就比较复杂。

deque的缺陷

与vector比较,deque的优势是:头部插入和删除时,不需要搬移元素,效率特别高,而且在扩容时,也不需要搬移大量的元素,因此其效率是必vector高的。
与list比较,其底层是连续空间,空间利用率比较高,不需要存储额外字段。
但是,deque有一个致命缺陷:不适合遍历,因为在遍历时,deque的迭代器要频繁的去检测其是否移动到某段小空间的边界,导致效率低下,而序列式场景中,可能需要经常遍历,因此在实际中,需要线性结构时,大多数情况下优先考虑vector和list,deque的应用并不多,而目前能看到的一个应用就是,STL用其作为stack和queue的底层数据结构

4.4 为什么选择deque作为stack和queue的底层默认容器

stack是一种后进先出的特殊线性数据结构,因此只要具有push_back()和pop_back()操作的线性结构,都可以作为stack的底层容器,比如vector和list都可以;queue是先进先出的特殊线性数据结构,只要具有push_back和pop_front操作的线性结构,都可以作为queue的底层容器,比如list。但是STL中对stack和queue默认选择deque作为其底层容器,主要是因为:
1. stack和queue不需要遍历(因此stack和queue没有迭代器),只需要在固定的一端或者两端进行操作。
2. 在stack中元素增长时,deque比vector的效率高(扩容时不需要搬移大量数据);queue中的元素增长时,deque不仅效率高,而且内存使用率高。
结合了deque的优点,而完美的避开了其缺陷。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/970369
推荐阅读
相关标签
  

闽ICP备14008679号