stack容器
stack是堆栈容器,是一种“先进后出”的容器。
#include <stack>
stack是基于deque容器而实现的容器
stack对象的默认构造
stack采用模板类实现, stack对象的默认构造形式: stack stkT;
stack stkInt; //一个存放int的stack容器。
stack stkFloat; //一个存放float的stack容器。
stack stkString; //一个存放string的stack容器。
…
//尖括号内还可以设置指针类型或自定义类型。
stack的push()与pop()方法
stack.push(elem); //往栈头添加元素
stack.pop(); //从栈头移除第一个元素
stack<int> stkInt;
stkInt.push(1);
stkInt.push(2);
stkInt.pop();
stkInt.push(3);
此时stkInt存放的元素是1, 3
stack对象的拷贝构造与赋值
stack(const stack &stk); //拷贝构造函数
stack& operator=(const stack &stk); //重载等号操作符
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(2);
stkIntA.push(3);
stack<int> stkIntB(stkIntA); //拷贝构造
stack<int> stkIntC;
stkIntC = stkIntA; //赋值
stack的数据存取
stack.top(); //返回最后一个压入栈元素
stack<int> stkIntA;
stkIntA.push(1);
stkIntA.push(2);
stkIntA.push(3);
int iTop = stkIntA.top(); //3
stkIntA.top() = 88; //88
stack的大小
stack.empty(); //判断堆栈是否为空
stack.size(); //返回堆栈的大小
stack<int> stkInt;
stkInt.push(1);
stkInt.push(2);
stkInt.push(3);
int iSize = stkInt.size(); //3
例子:
#include <iostream>
#include <stack>
#include <vector>
#include <list>
#include <queue>
#include <set>
using namespace std;
int main()
{
stack<int> stkInt; //默认使用deque 存储元素
//stack<int, vector<int>> stkInt; //使用vector 存储元素
//stack<int, list<int>> stkInt; //使用list 存储元素
//stack<int, queue<int>> stkInt; //不可以使用queue 存储元素
//stack<int, set<int>> stkInt; //不可以使用queue 存储元素
stkInt.push(1);
stkInt.push(2);
stkInt.push(3);
stkInt.pop(); //出3(后进先出)
stkInt.push(3);
int &iTop = stkInt.top(); //3
iTop = 66;
cout<<"stkInt.iTop: "<<stkInt.top()<<endl;
stkInt.top() = 88; //top() 返回的是引用 //88
cout<<"stkInt.top: "<<stkInt.top()<<endl;
cout<<"stkInt.size(): "<<stkInt.size()<<endl;
while(!stkInt.empty()) //不为空
{
cout<<stkInt.top()<<" ";
stkInt.pop(); //栈顶的元素出栈, 先进后出
}
cout<<endl;
system("pause");
return 0;
}
运行环境: vc++ 2010 学习版
运行结果: