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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值