c++STL栈的实现
时间: 2023-11-20 20:41:43 浏览: 48
C++ STL中的栈是通过标准库中的`<stack>`头文件实现的。在C++中,栈被定义为`stack<Type>`,其中`Type`是栈中存储的元素的类型。
栈的主要操作有:
- `push(a)`:将元素`a`推入栈顶。
- `pop()`:删除栈顶的元素,但不会返回被删除的元素。
- `top()`:返回栈顶的元素,但不会删除栈顶元素。
- `size()`:返回栈中元素的个数。
- `empty()`:检查栈是否为空,如果为空返回`true`,否则返回`false`。
在C++ STL中,栈的实现使用了容器适配器的概念。基于栈的默认实现,它使用了`deque`(双端队列)作为其底层容器,但也可以选择使用`vector`或`list`作为底层容器。这意味着栈提供了一种在底层容器上进行堆栈操作的统一接口,无论使用哪种容器作为底层实现。
对于自定义的栈实现,您可以参考以下示例代码:
```
#include <iostream>
#include <stack>
using namespace std;
class My_stack {
private:
stack<int> data;
public:
void push(int x) {
data.push(x);
}
int pop() {
int x = data.top();
data.pop();
return x;
}
int top() {
return data.top();
}
bool empty() {
return data.empty();
}
};
int main() {
My_stack s;
s.push(1);
s.push(2);
s.push(3);
cout << "Top element: " << s.top() << endl; // 输出栈顶元素
cout << "Pop element: " << s.pop() << endl; // 输出弹出的元素
cout << "Is stack empty? " << (s.empty() ? "Yes" : "No") << endl; // 检查栈是否为空
return 0;
}
```
以上是关于C++ STL栈的实现和用法的介绍。希望能对您有所帮助!