STL常用容器用法之——stack

来源:互联网 发布:mac 查看安装路径 编辑:程序博客网 时间:2024/06/14 02:19

Stack容器

stack是堆栈容器,是一种“先进后出”的容器。

stack是简单地装饰deque容器而成为另外的一种容器。

#include <stack>  

1、栈的生命周期

stack<int> s;


//入栈
for (int i=0; i<10; i++)
{
s.push(i+1);
}
cout << "栈的大小" << s.size() << endl; // 10


//出栈
while ( !s.empty())
{
int tmp = s.top(); //获取栈顶元素
cout <<  tmp << " "; // 10 9 8 7 6 5 4 3 2 1
s.pop(); //弹出栈顶元素 
}

2、stack对象的拷贝构造与赋值

stack(const stack &stk);               //拷贝构造函数

stack& operator=(const stack &stk);      //重载等号操作符

 

                   stack<int>stkIntA;

                   stkIntA.push(1);

                   stkIntA.push(3);

                   stkIntA.push(5);

                   stkIntA.push(7);

                   stkIntA.push(9);

 

                   stack<int>stkIntB(stkIntA);             //拷贝构造

                   stack<int>stkIntC;

                   stkIntC= stkIntA;                                //赋值

原创粉丝点击