C++中的栈
C++ 中的栈(Stack)
栈是一种遵循后进先出(LIFO)原则的数据结构,C++ 标准库(STL)提供了 std::stack
容器适配器来实现栈的功能。
基本用法
需要包含头文件 <stack>
,使用 std::stack
定义栈对象:
#include <stack>
std::stack<int> s; // 定义一个存储整型的栈
常用操作
压栈(Push):将元素添加到栈顶。
s.push(10); // 栈顶元素变为 10 s.push(20); // 栈顶元素变为 20
弹栈(Pop):移除栈顶元素(不返回其值)。
s.pop(); // 移除 20,栈顶元素变为 10
访问栈顶(Top):获取栈顶元素的值(不移除)。
int top_val = s.top(); // 获取 10
检查栈是否为空:
bool is_empty = s.empty(); // 返回 false(栈非空)
获取栈的大小:
size_t size = s.size(); // 返回当前元素数量
底层容器
std::stack
默认使用 std::deque
作为底层容器,但可以指定其他容器(如 std::vector
或 std::list
):
std::stack<int, std::vector<int>> s_vec; // 使用 vector 作为底层容器
注意事项
- 调用
top()
或pop()
前需确保栈非空,否则可能引发未定义行为。 - 栈不支持随机访问或迭代器操作。
示例代码
#include <iostream>
#include <stack>int main() {std::stack<int> s;s.push(1);s.push(2);s.push(3);while (!s.empty()) {std::cout << s.top() << " "; // 输出 3 2 1s.pop();}return 0;
}
手动实现栈
若需自定义栈,可以通过数组或链表实现。以下是基于数组的简化示例:
class CustomStack {
private:int* data;int capacity;int top_idx;public:CustomStack(int size) : capacity(size), top_idx(-1) {data = new int[capacity];}~CustomStack() { delete[] data; }void push(int val) {if (top_idx < capacity - 1) data[++top_idx] = val;}void pop() {if (top_idx >= 0) --top_idx;}int top() { return data[top_idx]; }bool empty() { return top_idx == -1; }
};
应用场景
- 函数调用栈(递归调用)
- 表达式求值(如括号匹配)
- 撤销操作(如编辑器中的 Ctrl+Z)
如需更高级功能(如线程安全),可考虑使用第三方库或自行扩展实现。