目录
这篇博客我们主要来学习一下stl的stack,queue,和priority_queue,它们分别是数据结构中的栈,队列和堆这篇博客我们还会了解到容器适配器模式和仿函数的写法。
list叫做容器,queue和stack叫容器适配器,我们看到它的模板参数就可以看出来,list的模板参数是一个空间配置器,stack和queue的模板参数是一个容器。

栈和我们之前学过的STL类模板对比来说,最大的不同是不支持迭代器,因为不是每种容器都需要迭代器去遍历,对于栈这种数据结构来说,迭代器遍历显得没那么重要。

如上图所示,它只提供了以上几个成员函数。
- void test_stack()
- {
- stack<int> s;
- s.push(1);
- s.push(2);
- s.push(3);
- s.push(4);
-
- while (!s.empty())
- {
- cout << s.top() << " ";
- s.pop();
- }
- cout << endl;
- }
栈的使用如上,我们向栈里面push了四个数据,每次打印栈顶的数据,然后将栈顶数据出栈,如此循环,直到栈为空。

queue也一样,它的成员函数也只有以下几个:

它的使用方式如下:
- void test_queue()
- {
- queue<int> q;
- q.push(1);
- q.push(2);
- q.push(3);
- q.push(4);
-
- while (!q.empty())
- {
- cout << q.front() << " ";
- q.pop();
- }
- cout << endl;
- }
我们先往队列里面push四个数据,然后打印队头的数据,接着是的队头数据出队列,如此循环,直到队列为空:

优先级队列,它的底层实际上一个堆(虽然它叫队列),它可以在任意位置插入数据,默认是一个大堆。

注意:
- 优先级队列不需要包括额外的头文件,只需要#include
就行了 - 优先级队列默认是一个大堆,这个时候只需要priority_queue
pq;就可以构造一个大堆,如果需要构造一个小堆,需要传入仿函数:priority_queue , greater > pq;
创建一个大堆:
- void test_priority_queue()
- {
- priority_queue<int> pq;
- pq.push(2);
- pq.push(5);
- pq.push(1);
- pq.push(6);
- pq.push(8);
-
- while (!pq.empty())
- {
- cout << pq.top() << " ";
- pq.pop();
- }
- cout << endl;
- }

创建一个小堆:
- void test_priority_queue()
- {
- priority_queue<int, vector<int>, greater<int>> pq;//仿函数,奇怪的是传的是greater这个仿函数来创建小堆
-
- pq.push(2);
- pq.push(5);
- pq.push(1);
- pq.push(6);
- pq.push(8);
-
- while (!pq.empty())
- {
- cout << pq.top() << " ";
- pq.pop();
- }
- cout << endl;
- }
-


- class MinStack {
- public:
- MinStack() {
-
- }
-
- void push(int val) {
- _st.push(val);
- if(_min.empty()||val<=_min.top())//最小栈没数据或插入的值小于等于最小值就让最小栈值进数据
- {
- _min.push(val);
- }
- }
-
- void pop() {
- if(_st.top()==_min.top())//如果栈顶数据和最小栈数据相等就让最小栈栈顶元素出栈
- {
- _min.pop();
- }
- _st.pop();
- }
-
- int top() {
- return _st.top();
- }
-
- int getMin() {
- return _min.top();
- }
- private:
- stack<int> _st;
- stack<int> _min;
-
- };

- class Solution {
- public:
- bool IsPopOrder(vector<int> pushV,vector<int> popV) {
- stack<int> st;
- int j = 0;
- for(int i = 0; i
size();i++) - {
- //入栈
- st.push(pushV[i]);
- while(!st.empty()&&st.top()==popV[j])
- {
- st.pop();
- j++;
- }
- }
- return st.empty();
- }
- };

- class Solution {
- public:
- int evalRPN(vector
& tokens) - {
- stack<int> s;//存储数字的栈
- for (size_t i = 0; i < tokens.size(); ++i)
- {
- string& str = tokens[i];//把vector
取出来看看是什么字符 - // str为数字
- if (!("+" == str || "-" == str || "*" == str || "/" == str))
- {
- s.push(atoi(str.c_str()));
- }
- else
- {
- // str为操作符
- int right = s.top();
- s.pop();
- int left = s.top();
- s.pop();
- switch (str[0])
- {
- case '+':
- s.push(left + right);
- break;
- case '-':
- s.push(left - right);
- break;
- case '*':
- s.push(left * right);
- break;
- case '/':
- s.push(left / right);
- break;
- }
- }
- }
- return s.top();
- }
- };
适配器是一种设计模式(设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总 结),该种模式是将一个类的接口转换成客户希望的另外一个接口。

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

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

stack和queue的模拟实现比较简单,只需要调用deque的库函数就可以实现适配:
- using namespace std;
- #include
- template<class T, class Container = deque
> - class stack
- {
- public:
- void push(const T& x)
- {
- _con.push_back(x);
- }
-
- void pop()
- {
- _con.popback();
- }
-
- const T& top()
- {
- return _con.back();//不要用[],因为别的容器不一定支持
- }
-
- size_t size()
- {
- return _con.size();
- }
-
- bool empty()
- {
- return _con.empty();
- }
-
- private:
- Container _con;
-
- };
大家可以试试用vector和list代替deque传参stack也能正常运行。
- template<class T, class Container = deque
> - class queue
- {
- public:
- void push(const T& x)
- {
- _con.push_back(x);
- }
-
- void pop()
- {
- _con.popfront();
- }
-
- const T& top()
- {
- return _con.back();//不要用[],因为别的容器不一定支持
- }
-
- size_t size()
- {
- return _con.size();
- }
-
- bool empty()
- {
- return _con.empty();
- }
-
- private:
- Container _con;
-
- };
queue就不能传vector代替deque传参了,因为人家没有实现popfront。
priority_queue默认的模板参数用的是vector,而不是deque,因为vector对随机访问的效率高,deque适合在头尾插入删除(虽然支持随机访问和中间的插入删除,但是效率比vector低)

priority_queue的模拟需要边插入边进行堆排序,我们需要回忆一下建立堆的博客,其实就是向上调整和向下调整,插入一个数据之后需要进行向上调整,pop掉一个数据之后需要进行向下调整。
- template<class T, class Container = vector
> - class priority_queue
- {
-
- public:
- void push(const T& x)
- {
- _con.push_back(x);
- AdjustUp(_con.size() - 1);//插入之后一个向上调整
-
- }
-
- void pop()
- {
- assert(_con.empty());
- swap(_con[0], _con[_con.size() - 1]);//先进先出,所以先把第一个位置的数据出掉,然后把交换后的第一个数据向下调整
- _con.pop_back();
- AdjustDown(0);
- }
-
-
- //
- //向上调整
- void AdjustUp(int child)//默认是大堆,用<用大堆
- {
- //找父亲
- int parent = (child - 1) / 2;
- while (child > 0)
- {
- //和父亲比较,如果父亲小于孩子,说明不是大堆,交换孩子和父亲
- if (_con[parent] < _con[child])
- {
- swap(_con[parent], _con[child]);
- //更新孩子和父亲的位置
- child = parent;
- parent = (child - 1) / 2;
- }
- else//不小就跳出
- {
- break;
- }
- }
- }
-
- //向下调整
- void AdjustDown(int parent)//默认是大堆,用<用大堆
- {
- //找孩子
- int child = parent * 2 + 1;//左孩子
- while (child < _con.size())
- {
- //选出左右孩子大的那个
- if (child + 1 < _con.size()&&_con[child]<_con[child+1])//右孩子存在且右孩子更大
- {
- child++;
-
- }
- if (_con[parent] < _con[child])
- {
- swap(_con[parent], _con[child]);
- parent = child;
- child = parent * 2 + 1;
- }
- else
- {
- break;
- }
- }
- }
-
- const T& top()//引用返回减少拷贝,且堆数据不允许随意修改,用const引用返回
- {
- return _con[0];
- }
-
- size_t size()
- {
- return _con.size();
- }
-
- bool empty()
- {
- return _con.empty();
- }
- private:
- Container _con;
- };
但是有个细节就是向上调整和向下调整不能写死,写死了创建小堆就很麻烦,像上面我们写死了就比较麻烦,创建小堆的时候如果写死了,就需要再定义一个创建小堆的向上调整和向下调整,但是实际使用中我们是传一个仿函数就行了。
因此我们先来写两个仿函数less和greater:
- template<class T>
- struct less
- {
- //重载的是()这个运算符
- bool operator()(const T& x, const T& y)const//const对象也能用
- {
- return x < y;
- }
- };
-
- template<class T>
- struct greater
- {
- //重载的是()这个运算符
- bool operator()(const T& x, const T& y)const//const对象也能用
- {
- return x > y;
- }
- };
如此看,使用起来就像一个函数,所以叫仿函数:
- less LessCom;
- cout << LessCom(1, 2) << endl;
-
- greater<int> GreaterCom;
- cout << GreaterCom(1, 2) << endl;
我们改造一下上面写的优先级队列,增加上仿函数作为模板参数:
- template<class T, class Container = vector
,class Compare = less> - class priority_queue
- {
- Compare comnFunc;
- public:
- void push(const T& x)
- {
- _con.push_back(x);
- AdjustUp(_con.size() - 1);//插入之后一个向上调整
-
- }
-
- void pop()
- {
- assert(_con.empty());
- swap(_con[0], _con[_con.size() - 1]);//先进先出,所以先把第一个位置的数据出掉,然后把交换后的第一个数据向下调整
- _con.pop_back();
- AdjustDown(0);
- }
-
-
- //
- //向上调整
- void AdjustUp(int child)//默认是大堆,用<用大堆
- {
-
- //找父亲
- int parent = (child - 1) / 2;
- while (child > 0)
- {
- //和父亲比较,如果父亲小于孩子,说明不是大堆,交换孩子和父亲
- if (comnFunc(_con[parent], _con[child]))
- {
- swap(_con[parent], _con[child]);
- //更新孩子和父亲的位置
- child = parent;
- parent = (child - 1) / 2;
- }
- else//不小就跳出
- {
- break;
- }
- }
- }
-
- //向下调整
- void AdjustDown(int parent)//默认是大堆,用<用大堆
- {
- Compare comnFunc;
- //找孩子
- int child = parent * 2 + 1;//左孩子
- while (child < _con.size())
- {
- //选出左右孩子大的那个
- if (child + 1 < _con.size()&& comnFunc(_con[child] ,_con[child + 1]))//右孩子存在且右孩子更大
- {
- child++;
-
- }
- if (comnFunc(_con[parent], _con[child]))
- {
- swap(_con[parent], _con[child]);
- parent = child;
- child = parent * 2 + 1;
- }
- else
- {
- break;
- }
- }
- }
-
- const T& top()//引用返回减少拷贝,且堆数据不允许随意修改,用const引用返回
- {
- return _con[0];
- }
-
- size_t size()
- {
- return _con.size();
- }
-
- bool empty()
- {
- return _con.empty();
- }
- private:
- Container _con;
- };
仿函数的优势是很多时候能够替代函数指针,函数指针其实是一个非常复杂的东西,一度令我很头疼,比如下面:

是不是感觉这么一大堆很复杂,和我们的仿函数比起来一点也不简洁,所以C++发明了仿函数。
greater和less两个仿函数是库里面已经为我们写好的,但是有时候我们需要自己显式写出一个仿函数,比如sort函数就需要用到自己写的仿函数:

假设我们有一个商品,需要我们进行排序,应该怎么办呢?
- // 商品
- struct Goods
- {
- string _name;//名字
- double _price;//价格
- size_t _saleNum;//销量
- };
Goods gds[4] = { { "苹果", 2.1, 1000}, { "香蕉", 3.0, 200}, { "橙子", 2.2,300}, { "菠萝", 1.5,50} };
以上的商品数组,你会如何排序呢?
那么这个时候就需要用到我们的仿函数了,根据我们排序的标准,去实现不同的仿函数,比如价格升序:
- // 商品
- struct Goods
- {
- string _name;//名字
- double _price;//价格
- size_t _saleNum;//销量
- };
-
- struct LessPrice//价格升序
- {
- bool operator()(const Goods& g1, const Goods& g2) const
- {
- return g1._price < g2._price;
- }
- };
-
- void testFunctional()
- {
- Goods gds[4] = { { "苹果", 2.1, 1000}, { "香蕉", 3.0, 200}, { "橙子", 2.2,300}, { "菠萝", 1.5,50} };
- sort(gds, gds + 4, LessPrice());
- }
运行结果为:

同理,也可以实现别的排序方式的仿函数:
- struct GreaterPrice//价格降序
- {
- bool operator()(const Goods& g1, const Goods& g2) const
- {
- return g1._price > g2._price;
- }
- };
-
- struct LessSaleNum//商品名字升序
- {
- bool operator()(const Goods& g1, const Goods& g2) const
- {
- return g1._saleNum < g2._saleNum;
- }
- };
-
-
- struct GreaterSaleNum//销量降序
- {
- bool operator()(const Goods& g1, const Goods& g2) const
- {
- return g1._saleNum > g2._saleNum;
- }
- };
deque是用来适配list和stack的容器适配器,我们进行一个简单的了解:

deque产生的理由是vector和list有一些共同的缺点:vector是连续的空间,优点是适合尾插尾删,适合随机访问,缺点是不适合头部或者中部的插入删除,效率低,需要挪动数据,此外vector扩容有一定性能的消耗,还可能存在一定程度的空间浪费。list是不连续的空间,优点是任意位置的插入删除效率高O(1),可以按需申请释放空间。缺点是不支持随机访问。

结合它们的优缺点,deque这个双端队列就应运而生。

它的结构如上图所示,它其实是一段段连续的空间,用一个叫做中控数组的指针数组记录每一段连续的空间的第一个位置,虽然中控数组满了也需要扩容,但是扩容的代价要比vector低得多。
deque的优缺点如下:

通过前面几节的学习,我们已经大概了解了适配器的这样一种模式,其实反向迭代器也是适配器模式。
我们想一想,反向迭代器和正向迭代器相比,有什么区别呢?好像除了++和--不一样,别的都一样,所以我们能不能用正向迭代器去封装适配一下,生成对应的反向迭代器呢?

源代码如下:
- template <class Iterator,class Ref,class Ptr>
- struct Reverse_iterator
- {
- Iterator _it;
- typedef Reverse_iterator
Self; - Reverse_iterator(Iterator _it)
- :_it(it)
- {
-
- }
- Ref operator*()
- {
- Iterator tmp = *it;
- return *(--tmp);
- }
-
- Ptr operator->()
- {
- return &(operator*());
- }
-
- Self& operator++()
- {
- --_it;
- return *this;
- }
-
- Self& operator--()
- {
- ++_it;
- return *this;
- }
-
- bool operator!=(const Self& s)
- {
- return _it != s._it;
- }
- };
-
- typedef __list_iterator
iterator; - typedef __list_iterator
const T&, const T*> const_iterator; -
- // 反向迭代器适配支持
- typedef Reverse_iterator
reverse_iterator; - typedef Reverse_iterator
const T&, const T*> const_reverse_iterator; -
- const_reverse_iterator rbegin() const
- {
- return const_reverse_iterator(end());
- }
-
- const_reverse_iterator rend() const
- {
- return const_reverse_iterator(begin());
- }
-
- reverse_iterator rbegin()
- {
- return reverse_iterator(end());
- }
-
- reverse_iterator rend()
- {
- return reverse_iterator(begin());
- }