STL 之栈
重要的数据结构。
操作:
- size() 返回实际个数
- empty() 判断是否为空
- push(item) 压栈
- top() 返回栈顶元素
- pop() 将栈顶元素删除
- s1.swap(s2) 将两个栈元素交互
- s1 == s1 判断是否相等
注:栈没有clear方法,若程序需要,可以单独编写!
示例代码:
#include <stack>
#include <iostream>
using namespace std;
int main() {
stack<int> intStack;
// 压 4个元素入栈
intStack.push(16);
intStack.push(8);
intStack.push(20);
intStack.push(3);
// 取栈顶元素,并弹栈
cout << "top of intStack:" << intStack.top() << endl;
intStack.pop();
cout << "top of intStack:" << intStack.top() << endl;
while(!intStack.empty()) {
cout << intStack.top() << " ";
intStack.pop();
}
cout << endl;
return 0;
}
运行结果:
top of intStack:3
top of intStack:20
20 8 16
top of intStack:20
20 8 16
浙公网安备 33010602011771号