9

Stack

  1. #if !defined( _STACK_H )
  2. #define _STACK_H
  3.  
  4. #include <assert.h>
  5.  
  6. template <class T>
  7. class Stack
  8. {
  9. public:
  10.     Stack( int s=100 ) : size( s ), top( 0 ) { data = new T[ size] ; }
  11.     ~Stack() { delete [] data; }
  12.     void push( const T& d ) { assert( top < size ); data[ top++ ] = d; }
  13.     T &pop( ) { assert( top > 0 ); return data[ --top ]; }
  14. private:
  15.     int top;
  16.     T *data;
  17.     unsigned size;
  18. };
  19.  
  20. #endif
  1. #include "Stack.h"
  2.  
  3. #if defined( STANDALONE )
  4.  
  5. #include <iostream>
  6.  
  7. int main()
  8. {
  9.     using std::cout;
  10.     using std::endl;
  11.  
  12.     {
  13.     Stack<int> stack;
  14.  
  15.     cout << "Pushing 1 then 2...\n";
  16.     stack.push( 1 );
  17.     stack.push( 2 );
  18.     cout << "Popping " << stack.pop();
  19.     cout << " then " << stack.pop() << endl;
  20.     cout << "Pushing 3...\n";
  21.     stack.push( 3 );
  22.     cout << "Popping " << stack.pop() << endl;
  23.     }
  24.     {
  25.     Stack<float> stack( 5 );
  26.  
  27.     cout << "Pushing 1.1 then 2.2...\n";
  28.     stack.push( 1.1 );
  29.     stack.push( 2.2 );
  30.     cout << "Popping " << stack.pop() << " then " << stack.pop() << endl;   // evaluated from right to left!
  31.     }
  32.     {
  33.     Stack<char *> stack;
  34.  
  35.     cout << "Pushing \"Aa\" then \"Bb\"...\n";
  36.     stack.push( "Aa" );
  37.     stack.push( "Bb" );
  38.     cout << "Popping " << stack.pop() << " then " << stack.pop() << endl;   // evaluated from right to left!
  39.     cout << "Popping one too many...\n";
  40.     stack.pop();    // aborts
  41.     }
  42. }
  43.  
  44. #endif

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].