C++中实现栈有两种方式:使用STL的std::stack容器适配器或数组模拟。std::stack默认基于deque,提供push、pop、top等接口,使用方便,适合工程开发;而数组模拟通过固定大小数组和topIndex变量手动管理栈顶位置,可精细控制内存,适合学习或资源受限场景。两者均遵循LIFO原则,但std::stack不支持遍历,若需随机访问应选用vector。根据需求选择合适方式即可。

在C++中,实现一个栈有两种常见方式:使用标准模板库(STL)中的 std::stack 容器适配器,或者通过数组手动模拟栈结构。下面分别介绍这两种方法的使用和实现方式。
std::stack 是 C++ STL 提供的一个容器适配器,底层默认基于 deque 实现,也可以指定为 vector 或 list。它只允许从一端进行插入和删除操作,符合“后进先出”(LIFO)原则。
常用操作接口:
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <stack>
using namespace std;
<p>int main() {
stack<int> s;</p><pre class='brush:php;toolbar:false;'>s.push(10);
s.push(20);
s.push(30);
while (!s.empty()) {
cout << "Top: " << s.top() << endl;
s.pop();
}
return 0;}
输出结果:
Top: 30 Top: 20 Top: 10
注意:pop() 不返回值,需先调用 top() 获取元素再执行 pop()。
如果希望更深入理解栈的工作原理,可以使用数组手动实现一个简单的栈。这种方式常用于算法题或嵌入式开发中对性能和内存有严格要求的场景。
基本结构:
简单实现示例:
#include <iostream>
using namespace std;
<p>class Stack {
private:
static const int MAX_SIZE = 100;
int data[MAX_SIZE];
int topIndex;</p><p>public:
Stack() : topIndex(-1) {}</p><pre class='brush:php;toolbar:false;'>void push(int value) {
if (topIndex >= MAX_SIZE - 1) {
cout << "Stack overflow!" << endl;
return;
}
data[++topIndex] = value;
}
void pop() {
if (isEmpty()) {
cout << "Stack underflow!" << endl;
return;
}
topIndex--;
}
int top() {
if (isEmpty()) {
cerr << "Stack is empty!" << endl;
return -1; // 可抛异常或设为错误码
}
return data[topIndex];
}
bool isEmpty() {
return topIndex == -1;
}
int size() {
return topIndex + 1;
}};
// 使用示例 int main() { Stack s; s.push(1); s.push(2); s.push(3);
while (!s.isEmpty()) {
cout << "Top: " << s.top() << endl;
s.pop();
}
return 0;}
输出结果:
Top: 3 Top: 2 Top: 1
该实现支持基本的栈操作,并加入了边界检查防止溢出。可根据需要扩展为动态扩容版本(类似 vector)。
基本上就这些。根据实际需求选择合适的方式即可。
以上就是C++怎么实现一个栈_C++ STL中std::stack容器的使用或数组模拟实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号