c++stack(堆栈)是一个容器的改编,它实现了一个先进后出的数据结构(FILO)html
使用该容器时须要包含#include<stack>头文件;ios
定义stack对象的示例代码以下:c++
stack<int>s1;数据结构
stack<string>s2;spa
stack的基本操做有:htm
1.入栈:如s.push(x);对象
2.出栈:如 s.pop().注意:出栈操做只是删除栈顶的元素,并不返回该元素。ip
3.访问栈顶:如s.top();string
4.判断栈空:如s.empty().当栈空时返回true。io
5.访问栈中的元素个数,如s.size();
下面举一个简单的例子:
#include<iostream> #include<stack> using namespace std; int main(void) { stack<double>s;//定义一个栈 for(int i=0;i<10;i++) s.push(i); while(!s.empty()) { printf("%lf\n",s.top()); s.pop(); } cout<<"栈内的元素的个数为:"<<s.size()<<endl; return 0; }