zoukankan      html  css  js  c++  java
  • Stack实现方式

    Stack的一种实现

    /*
     * stack实现:利用vector
     
    */
    #include <iostream>
    #include <vector>
    #include <string>

    using std::cout;
    using std::endl;
    using std::vector;
    using std::string;
    using std::ostream;

    template <class T>
    class Stack{
        public:
            Stack(int cap=0){
                if(cap)
                    _stack.reserve(cap);
            }
            bool pop(T &vaulue);
            bool push(T  value);
            bool full();
            bool empty();
            void display();
            int size();
        private:
            vector<T> _stack;
    };
    template<class T>
    inline int Stack<T>::size(){
        return _stack.size();
    }
    template<class T>
    inline bool Stack<T>::empty(){
        return _stack.empty();
    }
    template<class T>
    inline bool Stack<T>::full(){
        return _stack.max_size()==_stack.size();
    }
    template<class T>
    bool Stack<T>::pop(T &value){
        if(empty())
            return false;
        value=_stack.back();
        _stack.pop_back();
        cout<<"Stack:pop()"<<value<<endl;
        return true;
    }
    template<class T>
    bool Stack<T>::push(T value){
        if(full())
            return false;
        _stack.push_back(value);
        cout<<"Stack:push()"<<value<<endl;
        return true;

    }
    template<class T>
    void Stack<T>::display(){
        if(size()==0) { cout<<"(0)"<<endl;
        }
        else{
            cout<<"("<<size()<<")(bot:";
            for(int i=0;i<size();++i)
                cout<<_stack[i]<<" ";
            cout<<":top)"<<endl;
        }
    }
    class MyTest{
        friend ostream& operator<<(ostream& os,MyTest& mt){
            os<<mt.str;
            return os;
        }

        public:
            MyTest(string s=""):str(s){
                cout<<"constructor"<<endl;
            };
        private:
            string str;
    };
    int main()
    {
    //    Stack<int> stack( 32 );
    //    stack.display();
    //    for ( int ix = 1; ix < 51; ++ix )
    //    {
    //        if ( ix%2 == 0 )
    //            stack.push( ix );
    //        if ( ix%5 == 0 )
    //            stack.display();
    //        if ( ix%10 == 0) {
    //            int dummy;
    //            stack.pop( dummy ); stack.pop( dummy );
    //            stack.display();
    //        }
    //    }
         Stack<MyTest> stack(10);
         stack.display();
         stack.push(MyTest("hello"));
         stack.display();
        return 0;
    }
  • 相关阅读:
    页面可视化搭建 整理
    单页面应用(SPA)重新部署后,正在浏览的页面如何更新缓存?
    vim 使用
    浏览器缓存 知识点
    http 2.0 新特性
    GoJS 在 vue 项目中的使用
    详解Vue中watch的高级用法
    什么是 PWA?
    代码风格统一工具:EditorConfig 和 静态代码检查工具:ESLint
    vue-cli 3.x 使用
  • 原文地址:https://www.cnblogs.com/xkfz007/p/2653812.html
Copyright © 2011-2022 走看看