• <stack和queue>——《C++初阶》


    目录

    1. stack的介绍和使用

    1.1 stack的介绍

    1.2 stack的使用(OJ练习)

    1.3 stack的模拟实现

    2. queue的介绍和使用

    2.1 queue的介绍

     2.2 queue的使用

    2.3 queue的模拟实现

    3.1 priority_queue的介绍和使用

    3.1 priority_queue的介绍

    3.2 priority_queue的使用

    3.3 在OJ中的使用

    3.4 priority_queue的模拟实现

    4. 容器适配器

    4.1 什么是适配器

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

    4.3 deque的简单介绍(了解)

    4.3.2 deque的缺陷

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

    5.stack、queue、priority_queue 的使用测试:

    后记:●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!                                                                  ——By 作者:新晓·故知


    1. stack的介绍和使用

    1.1 stack的介绍

    stack的文档介绍链接:stack - C++ Reference
    翻译:
    1. stack是一种容器适配器,专门用在具有后进先出操作的上下文环境中,其删除只能从容器的一端进行元素的插入与提取操作。
    2. stack是作为容器适配器被实现的,容器适配器即是对特定类封装作为其底层的容器,并提供一组特定的成员函数来访问其元素,将特定类作为其底层的,元素特定容器的尾部(即栈顶)被压入和弹出。
    3. stack的底层容器可以是任何标准的容器类模板或者一些其他特定的容器类,这些容器类应该支持以下操作:
    empty:判空操作
    back:获取尾部元素操作
    push_back:尾部插入元素操作
    pop_back:尾部删除元素操作
    4. 标准容器vector、deque、list均符合这些需求,默认情况下,如果没有为stack指定特定的底层容器,默认情况下使用deque。

     

    1.2 stack的使用(OJ练习)

    (1)最小栈:

    1. class MinStack
    2. {
    3. public:
    4. void push(int x)
    5. {
    6. // 只要是压栈,先将元素保存到_elem中
    7. _elem.push(x);
    8. // 如果x小于_min中栈顶的元素,将x再压入_min中
    9. if (_min.empty() || x <= _min.top())
    10. _min.push(x);
    11. }
    12. void pop()
    13. {
    14. // 如果_min栈顶的元素等于出栈的元素,_min顶的元素要移除
    15. if (_min.top() == _elem.top())
    16. _min.pop();
    17. _elem.pop();
    18. }
    19. int top() { return _elem.top(); }
    20. int getMin() { return _min.top(); }
    21. private:
    22. // 保存栈中的元素
    23. std::stack<int> _elem;
    24. // 保存栈的最小值
    25. std::stack<int> _min;
    26. };
    1. class MinStack
    2. {
    3. public:
    4. //默认构造函数
    5. MinStack()
    6. {}
    7. void push(int val)
    8. {
    9. _st.push(val);
    10. if (_minst.empty() || val <= _minst.top())
    11. {
    12. _minst.push(val);
    13. }
    14. }
    15. void pop()
    16. {
    17. if (_st.top() == _minst.top())
    18. _minst.pop();
    19. _st.pop();
    20. }
    21. int top()
    22. {
    23. return _st.top();
    24. }
    25. int getMin()
    26. {
    27. return _minst.top();
    28. }
    29. private:
    30. stack<int> _st;
    31. stack<int> _minst;
    32. };
    33. /**
    34. * Your MinStack object will be instantiated and called as such:
    35. * MinStack* obj = new MinStack();
    36. * obj->push(val);
    37. * obj->pop();
    38. * int param_3 = obj->top();
    39. * int param_4 = obj->getMin();
    40. */

    (2) JZ31 栈的压入、弹出序列:

     思路:

    入栈序列先入栈,每次入栈以后,栈顶元素与出栈序列首元素比较,如果能匹配,出栈序列减减,并出栈;如果不能匹配,说明比较的这个数据可能还没入栈,入栈序列继续入栈。如果入栈序列已经全部入栈,则说明出战序列与入栈序列不匹配。

    1. class Solution
    2. {
    3. public:
    4. bool IsPopOrder(vector<int> pushV, vector<int> popV)
    5. {
    6. //入栈和出栈的元素个数必须相同
    7. if (pushV.size() != popV.size())
    8. return false;
    9. // 用s来模拟入栈与出栈的过程
    10. int outIdx = 0;
    11. int inIdx = 0;
    12. stack<int> s;
    13. while (outIdx < popV.size())
    14. {
    15. // 如果s是空,或者栈顶元素与出栈的元素不相等,就入栈
    16. while (s.empty() || s.top() != popV[outIdx])
    17. {
    18. if (inIdx < pushV.size())
    19. s.push(pushV[inIdx++]);
    20. else
    21. return false;
    22. }
    23. // 栈顶元素与出栈的元素相等,出栈
    24. s.pop();
    25. outIdx++;
    26. }
    27. return true;
    28. }
    29. };
    1. class Solution
    2. {
    3. public:
    4. bool IsPopOrder(vector<int> pushV, vector<int> popV)
    5. {
    6. stack<int> st;
    7. size_t popi = 0;
    8. for (auto e : pushV)
    9. {
    10. st.push(e);
    11. while (!st.empty() && st.top() == popV[popi])
    12. {
    13. ++popi;
    14. st.pop();
    15. }
    16. }
    17. return popi == popV.size(); //或return st.empty();
    18. }
    19. };

    (3)逆波兰表达式求值:

    1. class Solution
    2. {
    3. public:
    4. int evalRPN(vector& tokens)
    5. {
    6. stack<int> s;
    7. for (size_t i = 0; i < tokens.size(); ++i)
    8. {
    9. string& str = tokens[i];
    10. // str为数字
    11. if (!("+" == str || "-" == str || "*" == str || "/" == str))
    12. {
    13. s.push(atoi(str.c_str()));
    14. }
    15. else
    16. {
    17. // str为操作符
    18. int right = s.top(); s.pop();
    19. int left = s.top();
    20. s.pop();
    21. switch (str[0])
    22. {
    23. case '+':
    24. s.push(left + right);
    25. break;
    26. case '-':
    27. s.push(left - right);
    28. break;
    29. case '*':
    30. s.push(left * right);
    31. break;
    32. case '/':
    33. // 题目说明了不存在除数为0的情况
    34. s.push(left / right);
    35. break;
    36. }
    37. }
    38. }
    39. return s.top();
    40. }
    41. };
    1. class Solution
    2. {
    3. public:
    4. int evalRPN(vector& tokens)
    5. {
    6. stack<int> st;
    7. for (const auto& str : tokens)
    8. {
    9. if (str == "+" || str == "-"
    10. || str == "*" || str == "/")
    11. {
    12. int right = st.top();
    13. st.pop();
    14. int left = st.top();
    15. st.pop();
    16. switch (str[0])
    17. {
    18. case '+':
    19. st.push(left + right);
    20. break;
    21. case '-':
    22. st.push(left - right);
    23. break;
    24. case '*':
    25. st.push(left * right);
    26. break;
    27. case '/':
    28. st.push(left / right);
    29. break;
    30. default:
    31. break;
    32. }
    33. }
    34. else
    35. {
    36. st.push(stoi(str));
    37. }
    38. }
    39. return st.top();
    40. }
    41. };

    1.3 stack的模拟实现

    从栈的接口中可以看出,栈实际是一种特殊的vector,因此使用vector完全可以模拟实现stack。
    1. #include
    2. namespace bite
    3. {
    4. template<class T>
    5. class stack
    6. {
    7. public:
    8. stack() {}
    9. void push(const T& x) { _c.push_back(x); }
    10. void pop() { _c.pop_back(); }
    11. T& top() { return _c.back(); }
    12. const T& top()const { return _c.back(); }
    13. size_t size()const { return _c.size(); }
    14. bool empty()const { return _c.empty(); }
    15. private:
    16. std::vector _c;
    17. };
    18. }

    2. queue的介绍和使用

    2.1 queue的介绍

    queue的文档介绍链接: queue - C++ Reference
    翻译:
    1. 队列是一种容器适配器,专门用于在FIFO上下文(先进先出)中操作,其中从容器一端插入元素,另一端提取元素。
    2. 队列作为容器适配器实现,容器适配器即将特定容器类封装作为其底层容器类,queue提供一组特定的成员函数来访问其元素。元素从队尾入队列,从队头出队列。
    3. 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类。该底层容器应至少支持以下操作:
    empty:检测队列是否为空
    size:返回队列中有效元素的个数
    front:返回队头元素的引用
    back:返回队尾元素的引用
    push_back:在队列尾部入队列
    pop_front:在队列头部出队列
    4. 标准容器类deque和list满足了这些要求。默认情况下,如果没有为queue实例化指定容器类,则使用标准容器deque。

     

     2.2 queue的使用

    2.3 queue的模拟实现

    因为queue的接口中存在头删和尾插,因此使用vector来封装效率太低,故可以借助list来模拟实现queue,
    具体如下:

    1. #include
    2. namespace bite
    3. {
    4. template<class T>
    5. class queue
    6. {
    7. public:
    8. queue() {}
    9. void push(const T& x) {_c.push_back(x);}
    10. void pop() {_c.pop_front();}
    11. T& back() {return _c.back();}
    12. const T& back()const {return _c.back();}
    13. T& front() {return _c.front();}
    14. const T& front()const {return _c.front();}
    15. size_t size()const {return _c.size();}
    16. bool empty()const {return _c.empty();}
    17. private:
    18. std::list _c;
    19. };
    20. }

    3.1 priority_queue的介绍和使用

    3.1 priority_queue的介绍

    priority_queue文档介绍链接:queue - C++ Reference
    翻译:
    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的使用

    优先级队列默认使用vector作为其底层存储数据的容器,在vector上又使用了堆算法将vector中元素构造成堆的结构,因此priority_queue就是堆,所有需要用到堆的位置,都可以考虑使用priority_queue。注意: 默认情况下priority_queue是大堆
    函数声明
    接口说明
    priority_queue()/priority_queue(fifirst,
    last)
    构造一个空的优先级队列
    empty( )
    检测优先级队列是否为空,是返回 true ,否则返回
    false
    top( )
    返回优先级队列中最大 ( 最小元素 ) ,即堆顶元素
    push(x)
    在优先级队列中插入元素 x
    pop ()
    删除优先级队列中最大 ( 最小 ) 元素,即堆顶元素
    【注意】
    1. 默认情况下,priority_queue是大堆
    1. #include
    2. #include
    3. #include // greater算法的头文件
    4. void TestPriorityQueue()
    5. {
    6. // 默认情况下,创建的是大堆,其底层按照小于号比较
    7. vector<int> v{3,2,7,6,0,4,1,9,8,5};
    8. priority_queue<int> q1;
    9. for (auto& e : v)
    10. q1.push(e);
    11. cout << q1.top() << endl;
    12. // 如果要创建小堆,将第三个模板参数换成greater比较方式
    13. priority_queue<int, vector<int>, greater<int>> q2(v.begin(), v.end());
    14. cout << q2.top() << endl;
    15. }
    2. 如果在priority_queue中放自定义类型的数据,用户需要在自定义类型中提供> 或者< 的重载。
    1. class Date
    2. {
    3. public:
    4. Date(int year = 1900, int month = 1, int day = 1)
    5. : _year(year)
    6. , _month(month)
    7. , _day(day)
    8. {}
    9. bool operator<(const Date& d)const
    10. {
    11. return (_year < d._year) ||
    12. (_year == d._year && _month < d._month) ||
    13. (_year == d._year && _month == d._month && _day < d._day);
    14. }
    15. bool operator>(const Date& d)const
    16. {
    17. return (_year > d._year) ||
    18. (_year == d._year && _month > d._month) ||
    19. (_year == d._year && _month == d._month && _day > d._day);
    20. }
    21. friend ostream& operator<<(ostream& _cout, const Date& d)
    22. {
    23. _cout << d._year << "-" << d._month << "-" << d._day;
    24. return _cout;
    25. }
    26. private:
    27. int _year;
    28. int _month;
    29. int _day;
    30. };
    31. void TestPriorityQueue()
    32. {
    33. // 大堆,需要用户在自定义类型中提供<的重载
    34. priority_queue q1;
    35. q1.push(Date(2018, 10, 29));
    36. q1.push(Date(2018, 10, 28));
    37. q1.push(Date(2018, 10, 30));
    38. cout << q1.top() << endl;
    39. // 如果要创建小堆,需要用户提供>的重载
    40. priority_queue, greater> q2;
    41. q2.push(Date(2018, 10, 29));
    42. q2.push(Date(2018, 10, 28));
    43. q2.push(Date(2018, 10, 30));
    44. cout << q2.top() << endl;
    45. }

    3.3 OJ中的使用

    (1)数组中第K个大的元素:
    1. class Solution {
    2. public:
    3. int findKthLargest(vector<int>& nums, int k)
    4. {
    5. // 将数组中的元素先放入优先级队列中
    6. priority_queue<int> p(nums.begin(), nums.end());
    7. // 将优先级队列中前k-1个元素删除掉
    8. for(int i= 0; i < k-1; ++i)
    9. {
    10. p.pop();
    11. }
    12. return p.top();
    13. }
    14. };

     

    3.4 priority_queue的模拟实现

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

    4. 容器适配器

    4.1 什么是适配器

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

     

    4.2 STL标准库中stackqueue的底层结构

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

     还可以用list适配

    还可以用deque适配,但不推荐

    对于vector:

    优点:适合尾插尾删、随机访问,CPU高速缓存命中率高

    缺点:

    a.不适合头部插入或者中部插入,效率低需要挪动数据

    b.扩容有一定性能消耗,还可能存在一定程度的空间浪费

    对于list:

    优点:

    a.可以在任意位置插入、删除,效率高

    b.按需申请释放空间

    缺点:不支持随机访问,CPU高速缓存命中率低

    对于deque:

    优点:a.头部和尾部插入数据效率不错

    b.支持随机访问

    c.扩容代价小

    d.CPU缓存命中率高

    缺点:

    a.中部插入、删除效率低

    b.虽然支持随机访问,但是效率相比vector而言还有差距,频繁随机访问不太好

    4.3 deque的简单介绍(了解)

    4.3.1 deque的原理介绍
    deque(双端队列):是一种双开口的"连续"空间的数据结构,双开口的含义是:可以在头尾两端进行插入和删除操作,且时间复杂度为O(1),与vector比较,头插效率高,不需要搬移元素;与list比较,空间利用率比较高。
    deque并不是真正连续的空间,而是由一段段连续的小空间拼接而成的,实际deque类似于一个动态的二维数组,其底层结构如下图所示:
    双端队列底层是一段假象的连续空间,实际是分段连续的,为了维护其“整体连续”以及随机访问的假象,落在了deque的迭代器身上,因此deque的迭代器设计就比较复杂,如下图所示:

    那deque是如何借助其迭代器维护其假想连续的结构呢?  

    4.3.2 deque的缺陷

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

    4.4 为什么选择deque作为stackqueue的底层默认容器

    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的优点,而完美的避开了其缺陷。

    5.stack、queue、priority_queue 的使用测试:

    1. #include
    2. #include
    3. #include
    4. #include
    5. using namespace std;
    6. namespace std
    7. {
    8. void test_stack()
    9. {
    10. stack<int> s;
    11. s.push(1);
    12. s.push(2);
    13. s.push(3);
    14. s.push(4);
    15. while (!s.empty())
    16. {
    17. cout << s.top() << " ";
    18. s.pop();
    19. }
    20. cout << endl;
    21. }
    22. void test_queue()
    23. {
    24. queue<int> q;
    25. q.push(1);
    26. q.push(2);
    27. q.push(3);
    28. q.push(4);
    29. while (!q.empty())
    30. {
    31. cout << q.front() << " ";
    32. q.pop();
    33. }
    34. cout << endl;
    35. }
    36. void test_priority_queue()
    37. {
    38. //问题:优先级队列(priority_queue)默认大的优先级高,但传的是less仿函数,底层是一个大堆
    39. //如果想切换成小的优先级高,则传greater仿函数,底层是一个小堆,
    40. //这种设计是反过来的,设计有些违反常规
    41. //priority_queue pq; //默认是大堆
    42. priority_queue<int, vector<int>, greater<int>> pq; //greater 仿函数,默认小的优先级高,这里为小堆
    43. pq.push(6);
    44. pq.push(4);
    45. pq.push(7);
    46. pq.push(3);
    47. pq.push(1);
    48. pq.push(9);
    49. while (!pq.empty())
    50. {
    51. cout << pq.top() << " ";
    52. pq.pop();
    53. }
    54. cout << endl;
    55. }
    56. }
    57. int main()
    58. {
    59. //std::test_stack();
    60. //std::test_queue();
    61. std::test_priority_queue();
    62. return 0;
    63. }

      注:

     

     

    后记:
    ●由于作者水平有限,文章难免存在谬误之处,敬请读者斧正,俚语成篇,恳望指教!
                                                                      ——By 作者:新晓·故知

  • 相关阅读:
    Spring Boot集成Timefold Solver实现课程表编排
    神经网络系列---回归问题和分类问题
    时序预测 | Python实现ARIMA-LSTM差分自回归移动平均模型结合长短期记忆神经网络时间序列预测
    Pytest参数详解 — 基于命令行模式
    unity脚本_Input鼠标键盘 c#
    Rhino是强大的专业3D造型软件
    Spring Security(十八)--OAuth2:实现授权服务器(上)--环境准备以及骨架代码搭建
    分布式事务及CAP和BASE顶底
    柒微自动发卡系统源码
    2、搭建MyBatis
  • 原文地址:https://blog.csdn.net/m0_57859086/article/details/126200136