stack堆栈是一个后进先出的线性表,插入和删除都只能在表一端进行,插入元素的一端成为栈顶(stack top),而另一端则称为栈底(stack bottom),插入元素称为入栈(push),删除元素称为出栈或弹栈(pop)
使用该容器时需要包含#include<stack>头文件; 定义stack对象的示例代码如下: stack<int>s1; stack<string>s2;
stack的基本操作有: 1.入栈:如s.push(x); 2.出栈:如 s.pop().注意:出栈操作只是删除栈顶的元素,并不返回该元素。 3.访问栈顶:如s.top(); 4.判断栈空:如s.empty().当栈空时返回true。 5.访问栈中的元素个数,如s.size();
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(9);
cout<<s.top()<<endl;
cout<<s.size()<<endl;
cout<<s.empty()<<endl;
while(s.empty() != true)
{
cout<<s.top()<<" ";
s.pop();
}
cout<<endl;
return 0;
}