STL序列式容器之stack

本文介绍了STL中的stack数据结构,它遵循先进后出的原则。stack主要操作包括push(添加元素)和pop(移除元素)。默认底层容器为deque,但也可以使用list。由于stack的功能完全依赖于底部容器,因此它被归类为container adapter而非container。
摘要由CSDN通过智能技术生成

stack概述
stack是一种先进后出的数据结构。它只有一个出口,如下图所示,stack允许新增元素、移除元素、取得最顶端元素。取得最顶端元素。但除了最顶端外,没有任何其它方法可以存取stack的其它元素。换言之,stack不允许具有遍历的行为。
将元素推入stack的操作称为push,将元素推出stack的草操作称为pop.在这里插入图片描述
stack定义完整列表
以某种既有容器作为底部结构,将接口改变,使之符合“先进后出”的特点性,形成一个stack,是很容易得到的。deque是双向开口的数据结构,若以deque是双向开口的数据结构,若以deque为底部结构并封闭其头端开口,变轻而易举地形成一个stack。因此,SGI STL便以deque作为缺省情况下的stack底部结构,stack底部结构,stack的实现因而非常简单,源代码十分简短,本处完整列出。
由于stack是以底部容器完成其所有工作,而具有这种“修改某种接口,形成另一种风貌”之性质者,称为adapter(配接器),因此,STL stack往往不被归类为container(容器),而被归类为container adapter。

template<class T,class Seqence=deque<T>>
class stack
{
       //以下的 _STL_NULL_TMPL_ARGS会开展<>
       friend bool operator==_STL_NULL_TMPL_ARGS(const stack&,const stack&);
       friend bool operator<_STL_NULL_TMPL_ARGS(const stack&, const stack&);
public:
       typedef typename Sequence::value_type value_type;
       typedef typename Sequence::size_type size_type;
       typedef typename Sequence::reference reference;
       typedef typename Sequence::const_reference const_reference;
protected:
        Sequence c;//底层容器
public:
        //以下完全利用Sequence c的操作,完成stack的操作
        bool empty() const {return c.empty();}
        size_type size() const {return c.size();}
        reference top(){return c.back();}
        const_reference top() const {return c.back();}
        //deque是两头可进出,stack是末端进,末端出(所以后者先出)
        void push(const value_type& x){c.push_back(x);}
        void pop(){c.pop_back();}
};

template<class T,class Seqence>
bool operator==(const stack<T,Seqence>& x,const stack<T, Seqence>& y)
{
        return x.c==y.c; 
}

template<class T,class Sequence>
bool operator<(const stack<T,Sequence>& x, const stack<T, Seqence>& y)
{
     return x.c<y.c;
}

stack没有迭代器
以list作为stack的底层容器
除了deque之外,list也是双向开口的数据结构。上述stack源代码中使用的底层容器的函数有empty,size,back,push_back,pop_back,凡此种种,list都具备。因此,若以list为底部结构并封口其头端开口,一样能够轻易形成一个stack。
如:

#include<stack>
#include<list>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
    stack<int ,list<int>>istack;
    istack.push(1);
    istack.push(3);
    istack.puish(5);
    istack.push(7);

    cout<<istack.size()<<endl;//4
    cout<<sitack.top()<<endl;//7

    istack.pop();
    cout<<istack.top()<<end;//5
    istack.pop()
    cout<<istack.pop()<<endl;//3
    istack.pop();
    cout<<istack.pop()<<endl;//1
    cout<<istack.size()<<endl;.//1
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值