栈的使用

        栈和队列都是动态集合,且在其上进行DELETE操作所移除的元素是预先设定的。这次我们说栈的使用,栈(stack)实现的是一种后进先出策略,被删除的是最近插入的元素,stack的操作分为判断空栈、压入(push)、弹出(pop)。

       stack为容器,可以通过C++标准程序库来使用它,它的部分实现代码为:

namespace std {
    template <class T, class Container = deque<T> >
    class stack {
        public :
            typedef typename Container::value_type value_type;
            typedef typename Container::size_type size_type;
            typedef Container container_type;
        protected:
            Container c;
        public:
            //产生一个stack,并以容器cont内的元素为初值
            explicit stack(const Container& = Container());
            
            //判断空栈,是返回1,不是返回0
            bool empty() const              {return c.empty();}
            //返回栈的长度
            size_type size() const          {return c.size();}
            //将元素x压入栈
            void push(const value_type& x)  {c.push_back(x);}
            //将栈头的元素弹出
            void pop()                      {c.pop_back();}
            //返回栈头元素
            value_type& top()               {return c.back();}
            //返回栈头元素,且该返回元素不能修改
            const value_type& top() const   {return c.back();}
    };
    template <class T, class Container>
        bool operator==(const stack<T, Container>&,
                        const stack<T, Container>&);
    //...other comparison operators
}
在使用stack的时候必须包含头文件<stack>

接下来给出一个实例,这样能够让我们更清楚的了解怎么使用stack。

#include <iostream>
#include <stack>
using namespace std;

int main()
{
    //定义一个元素类型为整型的stack
    stack<int> st;

    //压入三个元素
    st.push(1);
    st.push(2);
    st.push(3);

    //打印和弹出stack内的两个元素
    cout << st.top() << ' ';
    st.pop();
    cout << st.top() << ' ';
    st.pop();

    //修改stack顶部元素
    st.top() = 77;

    //压入两个元素
    st.push(4);
    st.push(5);

    //弹出stack顶部元素
    st.pop();

    //输出和弹出剩余元素
    while(!st.empty()){
        cout << st.top() << ' ';
        st.pop();
    }
    cout << endl;
    return 0;
}
程序输出为:3 2 4 77 

参考书:《C++标准程序库》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值