stack容器
开发工具与关键技术:C++、VisualStudio
作者:何任贤
撰写时间:2019年06月20日
stack容器是比较特殊的容器,它是一种堆栈容器,堆栈的意思是先进后出,而stack就是一种
先进后出的容器。
先进后出是stack容器的特点,所以叫堆栈容器,我们也可以把stack容器看成一个栈。
而stack是简单的装饰deque容器得来的容器。
#include
#include
using namespace std;
void main()
{
stack s;
//入栈
for (int i = 0; i<10; i++)
{
s.push(i + 1);
}
cout << “栈的大小:” << s.size() << endl;
//出栈
while (!s.empty())
{
int tmp = s.top(); //获取栈顶元素
cout <<tmp << " ";
s.pop(); //弹出栈顶元素
}
cout << endl;
}
从代码中的注释和运行结果,我们可以知道stack容器为什么叫堆栈容器,因为stack容器拥有堆栈的特性。
class liu
{
public:
int age;
void printT()
{
cout << age << " ";
}
};
void main()
{
liu t1, t2, t3;
t1.age = 31;
t2.age = 32;
t3.age = 33;
stack<liu *> s; //栈中放入类的指针
s.push(&t1);
s.push(&t2);
s.push(&t3);
while (!s.empty())
{
liu *p = s.top();
p->printT();
s.pop();
}
cout << endl;
}
stack容器和其他容器不太一样,它是修饰deque容器而来的,它只有下图的那些操作,这些操作是修饰了
deque容器的。有兴趣的可以去看stack容器的定义。