STL 之栈

目录


重要的数据结构。

操作:

  1. size()                                          返回实际个数
  2. empty()                                       判断是否为空
  3. push(item)                                 压栈
  4. top()                                             返回栈顶元素
  5. pop()                                            将栈顶元素删除
  6. s1.swap(s2)                               将两个栈元素交互
  7. 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

原文地址:https://www.cnblogs.com/wjchang/p/3671647.html