堆栈是一种线性表,插入和删除操作只在表的一端进行,该端成为栈顶,另一端则称为栈底。元素的入栈和出栈都是在栈顶进行的,因此堆栈是一种后进先出表(LIFO)。C++ STL的堆栈泛化是通过现有的序列容器来实现的,默认使用的是双端队列deque的数据结构。在STL中,stack的元素出栈操作是不返回栈顶元素的,获得栈顶元素需要调用相应的取栈顶函数才能获得,这种分离的实现,是考虑到出栈函数若是直接返回栈顶元素,将会导致返回值的数据引用安全问题或者不必要的低效复制函数的调用。
主要有以下两种方式。
(1) stack()
stack<int> s;
(2) stack(const stack&)
复制构造函数。
stack<int,list<int>> s1;
stack<int,list<int>> s2(s1);
入栈函数为push函数,C++的STL是不预设堆栈的大小的,入栈函数不考虑堆栈空间是否为满,均将元素压入堆栈。
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
出栈函数为pop函数,该函数并没有判断堆栈是否为空,需要自行判断堆栈是否为空,才可以执行pop函数。
stack<int> s;
while(!s.empty())
{
s.pop();
}
堆栈stack容器的栈顶元素的读取函数为top函数,取栈顶元素也要判断堆栈是否为空,取出的栈顶元素才有意义。
cout<<s.top()<<endl;
s.pop();
栈顶判断是否为空利用函数empty。
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
while(!s.empty())
{
cout<<s.top()<<endl;//5、4、3、2、1
s.pop();
}
return 0;
}
堆栈元素的个数可以用size函数来获得。
#include<iostream>
#include<stack>
#include<list>
#define STACK_SIZE 100
using namespace std;
int main()
{
stack<int,list<int> > s;
if(s.size()<STACK_SIZE)
{
s.push(68);
}
if(s.size()<STACK_SIZE)
{
s.push(50);
}
if(s.size()<STACK_SIZE)
{
s.push(10);
}
while(!s.empty())
{
cout<<s.top()<<endl;//10/50/68
s.pop();
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u011000290/article/details/47785367