5

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

Commentaires

Votre commentaire :
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip aide 2000

Entrez un maximum de 2000 caractères.
Améliorez la présentation de votre texte avec les balises de formatage suivantes :
[p]paragraphe[/p], [b]gras[/b], [i]italique[/i], [u]souligné[/u], [s]barré[/s], [quote]citation[/quote], [pre]tel quel[/pre], [br]à la ligne,
[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]commande[/code], [code=langage]code source en c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].