STL之顺序容器适配器(栈的数组实现代码)
stack容器适配器的简介见:http://www.cnblogs.com/alan-forever/archive/2012/09/16/2687480.html
这份代码是用数组实现(也可以说是用vector实现,实质都一样!)
1 #include<iostream> 2 using namespace std; 3 4 template <typename Object> 5 class Stack 6 { 7 public: 8 enum { Capacity = 20 }; 9 10 Stack( ) 11 { 12 init( ); 13 } 14 //构造函数,调用init函数生成默认栈! 15 ~Stack( ) 16 { 17 theSize = 0; 18 delete [ ] data; 19 } 20 //析构函数。 21 int size( ) 22 { 23 return theSize; 24 } 25 //返回栈里面元素的数目。 26 bool empty( ) 27 { 28 return size() == 0; 29 } 30 //判断栈时候为空 31 void push( const Object & x ) 32 { 33 data[ theSize++ ] = x; 34 if( theSize == theCapacity ) 35 reserve( theSize ); 36 } 37 //进栈操作,因为用数组实现,为了防止数组开的不够,用了Vector自动变大的操作! 38 void reserve( int newCapacity ) 39 { 40 Object * oldArry = data; 41 theCapacity = 2 * newCapacity + 1; 42 data = new Object[ theCapacity ]; 43 44 for(int i = 0; i != size(); ++i) 45 { 46 data[ i ] = oldArry[ i ]; 47 } 48 delete [ ] oldArry; 49 } 50 //栈的容量自动变大的操作! 51 const Object top( ) const 52 { 53 return data[ theSize - 1 ]; 54 } 55 //返回栈顶元素。 56 void pop( ) 57 { 58 theSize--; 59 } 60 //弹出栈顶元素。 61 private: 62 Object * data; //数组! 63 int theSize; //栈的元素数目。 64 int theCapacity; //栈的最大容量。 65 66 void init( ) 67 { 68 theSize = 0; 69 theCapacity = Capacity; 70 data = new Object[ theCapacity ]; 71 } //默认函数。 72 }; 73 74 int main( ) 75 { 76 Stack<int> s; 77 cout << "输出默认生成的栈的元素的数目:" << endl; 78 cout << s.size( ) << endl; 79 int num, m; 80 cout << "输入需要压进栈的元素的数目:" << endl; 81 cin >> num; 82 for(int i = 1; i <= num; ++i) 83 { 84 cin >> m; 85 s.push( m ); 86 cout << "栈顶的元素:" << endl; 87 cout << s.top( ) << endl; 88 } 89 cout << "输出栈的大小:" << endl; 90 cout << s.size( ) << endl; 91 s.pop( ); 92 cout << "在pop操作之后,栈顶元素值为:" << endl; 93 cout << s.top( ) << endl; 94 cout << "在pop操作之后,栈的大小:" << endl; 95 cout << s.size( ) << endl; 96 cout << "栈的empty操作!" << endl; 97 if( s.empty( ) ) 98 cout << "It is empty!" << endl; 99 else 100 cout << "It is not empty!" << endl; 101 return 0; 102 }

浙公网安备 33010602011771号