跳到主要内容C++ 容器适配器:stack、queue 与 priority_queue 详解 | 极客日志C++算法
C++ 容器适配器:stack、queue 与 priority_queue 详解
C++ STL 容器适配器 stack、queue 和 priority_queue 分别实现后进先出、先进先出及优先级队列功能。stack 默认底层为 deque,支持 push/pop/top 操作;queue 支持头尾插入删除;priority_queue 基于 vector 构建堆结构。文章详细讲解各容器接口、典型应用场景(如最小栈、K 大元素)、模拟实现逻辑及 deque 作为底层容器的优势与原理。
www1.8K 浏览 C++ 容器适配器:stack、queue 与 priority_queue 详解
一、stack 的介绍及使用
1.1 stack 的介绍
- stack 是一种后进先出(LIFO)的数据结构。
- 底层默认使用
deque 实现,但可以指定其他容器(如 vector 或 list)。
头文件:#include <stack>。

1.2 stack 的使用
| 函数说明 | 接口说明 |
|---|
| stack() | 构造空的栈 |
| empty() | 检测 stack 是否为空 |
| size() | 返回 stack 中元素的个数 |
| top() | 返回栈顶元素的引用 |
| push() | 将元素 val 压入 stack 中 |
| pop() | 将 stack 中尾部的元素弹出 |
1.2.1 最小栈问题
参考题目:155. 最小栈 (LeetCode)
解题思路:
这道题要求时间复杂度是 O(1)。我们可以定义两个栈,一个栈叫做 _st,一个栈叫做 _minst。当 _st 中插入 5 时 _minst 中也插入 5;当 _st 中插入 4 时,_minst 也插入 4;当 _st 中插入 6 时,此时 _minst 中不用做更新,因为没有插入更小的值。此时 _st 中删除与 _minst 中相同的值,_minst 就跟着删,否则 _minst 不动。
代码实现:
class MinStack {
:
() {}
{
_st.(val);
(_minst.() || val <= _minst.())
_minst.(val);
}
{
(_st.() == _minst.())
_minst.();
_st.();
}
{ _st.(); }
{ _minst.(); }
:
stack<> _st;
stack<> _minst;
};
public
MinStack
void push(int val)
push
if
empty
top
push
void pop()
if
top
top
pop
pop
int top()
return
top
int getMin()
return
top
private
int
int
拓展: 我们插入时如果有许多的重复数据有什么优化方案呢?
答案是我们可以定义一个结构体,结构体中的变量一个是 int val,另一个是 int count 用来计数。
1.2.2 栈的压入、弹出序列
- 先入栈
pushi 位置的数据。
- 栈顶数据跟
popi 位置的数据比较,如果匹配则出栈 popi++。
如果不匹配就继续入栈。
class Solution {
public:
bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {
size_t pushi = 0, popi = 0;
stack<int> st;
while (pushi < pushV.size()) {
st.push(pushV[pushi++]);
while (!st.empty() && popV[popi] == st.top()) {
popi++;
st.pop();
}
}
return st.empty();
}
};
1.2.3 逆波兰表达式求值
- 遇到操作数则入栈。
- 遇到操作符,取栈顶两个数进行运算,运算结果继续入栈。
class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> s;
for (auto& str : tokens)
{
if ("+" == str || "-" == str || "*" == str || "/" == 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;
}
} else {
s.push(stoi(str));
}
}
return s.top();
}
};
1.3 stack 的模拟实现
template<class T, class Container = std::deque<T>>
class stack {
public:
stack() {}
void push(const T& val) { _con.push_back(val); }
void pop() { _con.pop_back(); }
T& top() { return _con.back(); }
size_t size() { return _con.size(); }
bool empty() { return _con.empty(); }
private:
Container _con;
};
二、queue 的介绍和使用
2.1 queue 的介绍
- 队列是一种容器适配器,专门用于在
FIFO 上下文(先进先出)中操作,其中从容器一端插入元素,另一端提取元素。
- 队列作为容器适配器实现,容器适配器即将特定容器类封装作为其底层容器类,
queue 提供一组特定的成员函数来访问其元素。元素从队尾入队列,从队头出队列。
- 底层容器可以是标准容器类模板之一,也可以是其他专门设计的容器类。该底层容器应至少支持以下操作:
empty:检测队列是否为空
size:返回队列中有效元素的个数
front:返回队头元素的引用
back:返回队尾元素的引用
push_back:在队列尾部入队列
pop_front:在队列头部出队列
标准容器类 deque 和 list 满足了这些要求。默认情况下,如果没有为 queue 实例化指定容器类,则使用标准容器 deque。
2.2 queue 的使用
| 函数声明 | 接口说明 |
|---|
| queue() | 构造空的队列 |
| empty() | 检测队列是否为空,是返回 true,否则返回 false |
| size() | 返回队列中有效元素的个数 |
| front() | 返回队头元素的引用 |
| back() | 返回队尾元素的引用 |
| push() | 在队尾将元素 val 入队列 |
| pop() | 将队头元素出队列 |
2.3 queue 的模拟实现
queue 中因为要支持头删,所以就不能用 vector。
template<class T, class Container = std::list<T>>
class queue {
public:
queue() {}
void push(const T& val) { _con.push_back(val); }
void pop() { _con.pop_front();
T& front() { return _con.front(); }
T& back() { return _con.back(); }
size_t size() { return _con.size(); }
bool empty() { return _con.empty(); }
private:
Container _con;
};
三、priority_queue 的介绍和使用
3.1 priority_queue 的介绍
- 优先队列是一种容器适配器,根据严格的弱排序标准,它的第一个元素总是它所包含的元素中最大的。
- 此上下文类似于堆,在堆中可以随时插入元素,并且只能检索最大堆元素(优先队列中位于顶部的元素)。
- 优先队列被实现为容器适配器,容器适配器即将特定容器类封装作为其底层容器类。元素从特定容器的'尾部'弹出,其称为优先队列的顶部。
- 底层容器可以是任何标准容器类模板,也可以是其他特定设计的容器类。容器应该可以通过随机访问迭代器访问,并支持以下操作:
empty()、size()、front()、push_back()、pop_back()。
- 标准容器类
vector 和 deque 满足这些需求。默认情况下,如果没有为特定的 priority_queue 类实例化指定容器类,则使用 vector。
- 需要支持随机访问迭代器,以便始终在内部保持堆结构。容器适配器通过在需要时自动调用算法函数
make_heap、push_heap 和 pop_heap 来自动完成此操作。
3.2 priority_queue 的使用
优先级队列默认使用 vector 作为其底层存储数据的容器,在 vector 上又使用了堆算法将 vector 中元素构造成堆的结构,因此 priority_queue 就是堆,所有需要用到堆的位置,都可以考虑使用 priority_queue。注意:默认情况下 priority_queue 是大堆。
| 函数声明 | 接口说明 |
|---|
| priority_queue()/priority_queue(first,last) | 构造一个空的优先级队列 |
| empty() | 检测优先级队列是否为空,是返回 true,否则返回 false |
| top() | 返回优先级队列中最大 (最小元素),即堆顶元素 |
| push(x) | 在优先级队列中插入元素 x |
| pop() | 删除优先级队列中最大 (最小) 元素,即堆顶元素 |
【注意】: 默认情况下,priority_queue 是大堆。
3.3 在 OJ 中的使用
解题思路:
将数组放入优先级队列中,优先级队列的第一个元素是最大的,要第 k 大,则只需要 pop k-1 次。
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
priority_queue<int> p(nums.begin(), nums.end());
while (--k)
p.pop();
return p.top();
}
};
3.4 priority_queue 的模拟实现
#include<vector>
namespace myPriorityQueue {
template<class T, class Container = std::vector<T>>
class priority_queue {
public:
void AdjustUp(int child) {
int parent = (child - 1) / 2;
while (child > 0) {
if (_con[child] > _con[parent]) {
swap(_con[child], _con[parent]);
child = parent;
parent = (parent - 1) / 2;
} else {
break;
}
}
}
void AdjustDown(int parent) {
int child = parent * 2 + 1;
while (child < _con.size()) {
if (child + 1 < _con.size() && _con[child + 1] > _con[child])
++child;
if (_con[child] > _con[parent])
{
swap(_con[child], _con[parent]);
parent = child;
child = parent * 2 + 1;
} else {
break;
}
}
}
void push(const T& x) {
_con.push_back(x);
AdjustUp(_con.size() - 1);
}
void pop() {
swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
AdjustDown(0);
}
bool empty() { return _con.empty(); }
const T& top() { return _con[0];
size_t size() { return _con.size(); }
private:
Container _con;
};
}
加上仿函数版本的:
首先来看什么是仿函数:仿函数是一种可以像函数一样被调用的对象,仿函数是一个类或者结构体,它重载了 operator(),使其可以向函数一样被调用。
库里面传 < 是大堆,传 > 是小堆,为了保持和库里面的是一致的,所以我们也这样实现。
namespace myPriorityQueue {
template<class T>
struct less
{
bool operator()(const T& x, const T& y) const {
return x < y;
}
};
template<class T>
struct greater
{
bool operator()(const T& x, const T& y) const {
return x > y;
}
};
template<class T, class Container = std::vector<T>, class Compare = greater<T>>
class priority_queue {
public:
priority_queue() = default;
template<class InputIterator>
priority_queue(InputIterator first, InputIterator last) : _con(first, last) {
for (int i = (_con.size() - 1 - 1) / 2; i >= 0; i--)
AdjustDown(i);
}
void AdjustUp(int child) {
Compare com;
int parent = (child - 1) / 2;
while (child > 0) {
if (com(_con[parent], _con[child]))
{
swap(_con[child], _con[parent]);
child = parent;
parent = (parent - 1) / 2;
} else {
break;
}
}
}
void AdjustDown(int parent) {
Compare com;
int child = parent * 2 + 1;
while (child < _con.size()) {
if (child + 1 < _con.size() && com(_con[child], _con[child + 1]))
++child;
if (com(_con[parent], _con[child]))
{
swap(_con[child], _con[parent]);
parent = child;
child = parent * 2 + 1;
} else {
break;
}
}
}
void push(const T& x) {
_con.push_back(x);
AdjustUp(_con.size() - 1);
}
void pop() {
swap(_con[0], _con[_con.size() - 1]);
_con.pop_back();
AdjustDown(0);
}
bool empty() { return _con.empty(); }
const T& top() { return _con[0];
size_t size() { return _con.size(); }
private:
Container _con;
};
}
四、容器适配器
4.1 什么是适配器
适配器是一种设计模式(设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结),该种模式是将一个类的接口转换成客户希望的另外一个接口。
4.2 STL 标准库中 stack 和 queue 的底层结构
虽然 stack 和 queue 中也可以存放元素,但在 STL 中并没有将其划分在容器的行列,而是将其称为容器适配器,这是因为 stack 和队列只是对其他容器的接口进行了包装。STL 中 stack 和 queue 默认使用 deque。
五、deque 的介绍
5.1 deque 的原理介绍
deque(双端队列):是一种双开口的"连续"空间的数据结构,双开口的含义是:可以在头尾两端进行插入和删除操作,且时间复杂度为 O(1)。与 vector 比较,头插效率高,不需要搬移元素;与 list 比较,空间利用率比较高。
deque 并不是真正连续的空间,而是由一段段连续的小空间拼接而成的,实际 deque 类似于一个动态的二维数组,其底层结构如下图所示。
双端队列底层是一段假象的连续空间,实际是分段连续的,为了维护其'整体连续'以及随机访问的假象,落在了 deque 的迭代器身上,因此 deque 的迭代器设计就比较复杂。
那 deque 是如何借助其迭代器维护其假想连续的结构呢?
5.2 deque 的缺陷
- 与 vector 比较,
deque 的优势是:头部插入和删除时,不需要搬移元素,效率特别高,而且在扩容时,也不需要搬移大量的元素,因此其效率是比 vector 高的。
- 与 list 比较,其底层是连续空间,空间利用率比较高,不需要存储额外字段。
- 但是,deque 有一个致命缺陷:不适合遍历,因为在遍历时,
deque 的迭代器要频繁的去检测其是否移动到某段小空间的边界,导致效率低下。而序列式场景中,可能需要经常遍历,因此在实际中,需要线性结构时,大多数情况下优先考虑 vector 和 list,deque 的应用并不多。而目前能看到的一个应用就是,STL 用其作为 stack 和 queue 的底层数据结构。
deque 之所以不能替代 vector 和 List 是因为:下标访问没有 vector 效率高,中间插入删除没有 list 效率高。
5.3 为什么选择 deque 作为 stack 和 queue 的底层默认容器
stack 是一种后进先出的特殊线性数据结构,因此只要具有 push_back() 和 pop_back() 操作的线性结构,都可以作为 stack 的底层容器,比如 vector 和 list 都可以;queue 是先进先出的特殊线性数据结构,只要具有 push_back 和 pop_front 操作的线性结构,都可以作为 queue 的底层容器,比如 list。但是 STL 中对 stack 和 queue 默认选择 deque 作为其底层容器,主要是因为:
- stack 和 queue 不需要遍历(因此 stack 和 queue 没有迭代器),只需要在固定的一端或者两端进行操作。
- 在 stack 中元素增长时,
deque 比 vector 的效率高(扩容时不需要搬移大量数据);queue 中的元素增长时,deque 不仅效率高,而且内存使用率高。
相关免费在线工具
- 加密/解密文本
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
- Gemini 图片去水印
基于开源反向 Alpha 混合算法去除 Gemini/Nano Banana 图片水印,支持批量处理与下载。 在线工具,Gemini 图片去水印在线工具,online
- Base64 字符串编码/解码
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
- Base64 文件转换器
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
- Markdown转HTML
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online
- HTML转Markdown
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML转Markdown在线工具,online