欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Stack实现方式

发布时间:2025/3/19 编程问答 30 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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;
}

转载于:https://www.cnblogs.com/xkfz007/archive/2012/08/24/2653812.html

总结

以上是生活随笔为你收集整理的Stack实现方式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。