C++中stack和queue是STL提供的容器适配器,分别用于实现后进先出(LIFO)和先进先出(FIFO)操作。stack支持push、pop、top等操作,常用于括号匹配等场景;queue提供front、back、push、pop等功能,适用于层序遍历(BFS)等应用。两者均需包含对应头文件并注意访问前判空,避免运行时错误。

在C++中,stack(栈)和queue(队列)是两种常用的数据结构,它们被包含在标准模板库(STL)中,分别定义于#include 和#include 头文件。虽然底层可以用vector、deque或list实现,但它们提供了一种更安全、更语义化的接口来处理“后进先出”和“先进先出”的逻辑。
stack 栈的基本使用
栈是一种后进先出(LIFO, Last In First Out)的数据结构。C++中的std::stack是一个容器适配器,它不支持遍历,只允许从一端(栈顶)进行操作。
常用操作包括:
- push(element):将元素压入栈顶
- pop():移除栈顶元素(不返回值)
- top():获取栈顶元素的引用
- empty():判断栈是否为空
- size():返回栈中元素个数
示例代码:
#include <stack><br>#include <iostream>
int main() {
std::stack<int> s;
s.push(10);
s.push(20);
s.push(30);
<pre class="brush:php;toolbar:false;">while (!s.empty()) {
std::cout <p>}</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13188" title="Build n8n workflows from node docs, templates, and schemas through MCP"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20d3191a227.jpg" alt="Build n8n workflows from node docs, templates, and schemas through MCP" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13188" title="Build n8n workflows from node docs, templates, and schemas through MCP" class="overflowclass">Build n8n workflows from node docs, templates, and schemas through MCP</a>
<p class="overflowclass">当代理需要在设计或调试工作流时结构化访问 n8n 节点、属性、操作和模板示例时,请使用 n8n-MCP,而不是通过原始文档猜测或手动点击 n8n UI。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13188" title="Build n8n workflows from node docs, templates, and schemas through MCP" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>queue 队列的基本使用
队列遵循先进先出(FIFO, First In First Out)原则。C++中的std::queue也是容器适配器,默认基于deque实现。
主要操作有:
- push(element):在队尾添加元素
- pop():删除队首元素(不返回值)
- front():访问队首元素
- back():访问队尾元素
- empty() 和 size():与stack一致
示例代码:
#include <queue><br>#include <iostream>
int main() {
std::queue<int> q;
q.push(10);
q.push(20);
q.push(30);
<pre class="brush:php;toolbar:false;">while (!q.empty()) {
std::cout <p>}</p>实战应用场景举例
stack和queue在算法题和系统设计中非常实用。
使用 stack 判断括号匹配
遍历字符串,遇到左括号入栈,右括号时检查栈顶是否匹配并弹出。
bool isValid(std::string s) {
std::stack<char> st;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
st.push(c);
} else {
if (st.empty()) return false;
if ((c == ')' && st.top() != '(') ||
(c == ']' && st.top() != '[') ||
(c == '}' && st.top() != '{')) {
return false;
}
st.pop();
}
}
return st.empty();
}
</char>使用 queue 实现层序遍历(BFS)
二叉树的广度优先搜索依赖队列保存待访问节点。
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
<p>void bfs(TreeNode<em> root) {
if (!root) return;
std::queue<treenode>> q;
q.push(root);</treenode></em></p><pre class="brush:php;toolbar:false;">while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
std::cout val left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
基本上就这些。掌握stack和queue的接口和典型用法,能显著提升编码效率,特别是在处理递归模拟、状态暂存、广度搜索等场景时。注意不要误用top()或front()前未判空,否则会引发运行时错误。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










