5
Stack
- #if !defined( _STACK_H )
- #define _STACK_H
- #include <assert.h>
- template <class T>
- class Stack
- {
- public:
- Stack( int s=100 ) : size( s ), top( 0 ) { data = new T[ size] ; }
- ~Stack() { delete [] data; }
- void push( const T& d ) { assert( top < size ); data[ top++ ] = d; }
- T &pop( ) { assert( top > 0 ); return data[ --top ]; }
- private:
- int top;
- T *data;
- unsigned size;
- };
- #endif
- #include "Stack.h"
- #if defined( STANDALONE )
- #include <iostream>
- int main()
- {
- using std::cout;
- using std::endl;
- {
- Stack<int> stack;
- cout << "Pushing 1 then 2...\n";
- stack.push( 1 );
- stack.push( 2 );
- cout << "Popping " << stack.pop();
- cout << " then " << stack.pop() << endl;
- cout << "Pushing 3...\n";
- stack.push( 3 );
- cout << "Popping " << stack.pop() << endl;
- }
- {
- Stack<float> stack( 5 );
- cout << "Pushing 1.1 then 2.2...\n";
- stack.push( 1.1 );
- stack.push( 2.2 );
- cout << "Popping " << stack.pop() << " then " << stack.pop() << endl; // evaluated from right to left!
- }
- {
- Stack<char *> stack;
- cout << "Pushing \"Aa\" then \"Bb\"...\n";
- stack.push( "Aa" );
- stack.push( "Bb" );
- cout << "Popping " << stack.pop() << " then " << stack.pop() << endl; // evaluated from right to left!
- cout << "Popping one too many...\n";
- stack.pop(); // aborts
- }
- }
- #endif
Commentaires