跳到主要内容
版本:1.0

stack

std::stack 是 C++ 标准库中的容器适配器,遵循后进先出(LIFO, Last In First Out)规则。

它就像一摞盘子:最后放上去的元素,最先被取走。

头文件与基本特征

使用 stack 时,需要包含头文件:

#include <stack>

stack 的常见特征如下:

特征说明
类型容器适配器
访问位置仅栈顶
入栈push()
出栈pop()
顺序规则后进先出(LIFO)
默认底层容器std::deque

基本用法

#include <stack>

int main() {
std::stack<int> st;

st.push(10);
st.push(20);
st.push(30);

st.pop(); // 弹出 30

return 0;
}

常用成员函数

函数作用
push(x)元素入栈
pop()栈顶元素出栈
top()访问栈顶元素
size()当前元素个数
empty()判断是否为空

遍历说明

stack 不提供迭代器,通常通过复制一份后反复 top()+pop() 来查看元素:

#include <iostream>
#include <stack>

int main() {
std::stack<int> st;
st.push(1);
st.push(2);
st.push(3);

std::stack<int> tmp = st;
while (!tmp.empty()) {
std::cout << tmp.top() << ' ';
tmp.pop();
}
std::cout << '\n';

return 0;
}

输出顺序是 3 2 1,体现了 LIFO 规则。

典型场景

stack 常用于:

  1. 表达式求值、括号匹配。
  2. 函数调用栈模型理解。
  3. 深度优先搜索(DFS)的显式栈实现。
  4. 撤销/回退(undo)等“最近操作优先恢复”的逻辑。

使用注意

  1. pop() 不返回值,先 top()pop()
  2. top() 前要确保栈非空。
  3. 如果需要“先进先出”语义,应使用 queue 而不是 stack