概念
STL(标准模板库)中的 stack
是 C++ 中的栈容器。实现了栈的基本功能。
主要特点
- **先进后出 (LIFO)**:
stack
是一种先进后出(LIFO)数据结构,元素的插入和删除都在同一端进行,即栈顶。
- 底层实现:
stack
通常使用双端队列(deque
)或链表作为底层实现。
- 限制操作:只能访问栈顶元素(
top()
)、进行入栈(push()
)和出栈(pop()
)操作。
基本用法
1. 创建和初始化
1 2 3 4 5 6 7 8 9 10 11
| #include <stack> #include <iostream>
using namespace std;
int main() { stack<int> s;
return 0; }
|
2. 元素操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| #include <stack> #include <iostream>
using namespace std;
int main() { stack<int> s;
s.push(1); s.push(2); s.push(3);
cout << "Top: " << s.top() << endl;
s.pop();
cout << "Top: " << s.top() << endl;
return 0; }
|
3. 检查栈的状态
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <stack> #include <iostream>
using namespace std;
int main() { stack<int> s;
if (s.empty()) { cout << "Stack is empty." << endl; }
s.push(1);
cout << "Size: " << s.size() << endl;
return 0; }
|
常用成员函数
元素操作:
push(const T& value)
:在栈顶插入一个元素。
pop()
:移除栈顶元素。
top()
:返回栈顶元素的引用。
状态检查:
empty()
:检查栈是否为空,返回布尔值。
size()
:返回栈中元素的数量。