C++ 栈与队列的使用与模拟实现
在 C++ STL 中,stack 和 queue 是两个基础且实用的数据结构组件。与 vector、list 等直接容器不同,它们属于'容器适配器'。这意味着它们通过封装现有容器(如 vector、list 或 deque),限制接口功能来适配特定的数据结构需求。
一、STL 中的使用
两者的接口设计非常直观,主要围绕入栈/出队、访问顶部/前端元素以及判空操作展开。
#include <stack>
#include <iostream>
using namespace std;
int main() {
stack<int> st;
st.push(1);
st.push(2);
st.push(3);
while (!st.empty()) {
cout << st.top() << " "; // 输出顺序:3 2 1
st.pop();
}
return 0;
}
运行结果会遵循后进先出(LIFO)原则。在实际开发中,利用 STL 可以大幅减少重复造轮子的时间。例如在解决'用栈实现队列'这类算法题时,直接使用两个栈配合即可轻松完成逻辑转换,无需手动管理内存。
二、Stack 模拟实现
既然理解了它是容器适配器,我们可以尝试自己封装一个。最直接的底层选择是 vector。
template<class T, class Con = std::vector<T>>
class stack {
public:
stack() {}
void push(const T& x) {
_c.push_back(x);
}
void pop {
_c.();
}
{
_c.();
}
{
_c.();
}
{
_c.();
}
{
_c.();
}
:
Con _c;
};


