输出:0 3 2 1
STL 中栈的使用方法(stack)
基本操作:
stack.push(x) 将x加入栈stack中,即入栈操作; push() 函数将 val 值压栈,使其成为栈顶的第一个元素。
stack.pop() 出栈操作(删除栈顶),只是出栈,没有返回值;pop() 函数移除堆栈中最顶层元素。
stack.top() 返回第一个元素(栈顶元素),元素并未出栈;top() 函数返回对栈顶元素的引用。“==” “<=” “>=” “<” “>” “!=”
stack.size() 返回栈中的元素个数;size() 函数返当前堆栈中的元素数目。
stack.empty() 当栈为空时,返回 true; stack.empty() 当栈为空时,返回 true;
使用方法:
#include
using namespace std;
定义方法为:
stacks1; //入栈元素为 int 型
stacks2; // 入队元素为string型
stacks3; //入队元素为自定义型
#include <iostream>
#include <stack>
using namespace std;
int main()
{
//创建堆栈对象
stack<int> s;
//元素入栈
s.push(1);
s.push(2);
s.push(3);
s.push(0);
//元素出栈
while (!s.empty()) {
//打印栈顶元素
printf("%d ", s.top());
//出栈
s.pop();
}
return 0;
}