Generic Stack : generic stack « template « C++ Tutorial






#include <iostream>
using std::cout;
using std::endl;

template< typename T >
class Stack 
{
public:
    template< typename T >
    Stack( int s ): size( s > 0 ? s : 10 ),top( -1 ),stackPtr( new T[ size ] ){

    }


   ~Stack() 
   { 
      delete [] stackPtr;
   }

    bool push( const T &pushValue )
    {
       if ( !isFull() ) 
       {
          stackPtr[ ++top ] = pushValue;
          return true;
       }
    
       return false;
    }
    bool pop( T &popValue )
    {
       if ( !isEmpty() ) 
       {
          popValue = stackPtr[ top-- ];
          return true;
       }
    
       return false;
    }
   bool isEmpty() const 
   { 
      return top == -1; 
   }

   bool isFull() const 
   { 
      return top == size - 1; 
   }

private:
   int size;
   int top; 
   T *stackPtr;
};

int main()
{
   Stack< double > doubleStack( 5 ); // size 5
   double doubleValue = 1.1;

   cout << "Pushing elements onto doubleStack\n";

   while ( doubleStack.push( doubleValue ) ) 
   { 
      cout << doubleValue << ' ';
      doubleValue += 1.1;
   }

   while ( doubleStack.pop( doubleValue ) )
      cout << doubleValue << ' ';

   Stack< int > intStack; // default size 10
   int intValue = 1;
   cout << "\nPushing elements onto intStack\n";

   while ( intStack.push( intValue ) ) 
   {
      cout << intValue << ' ';
      intValue++;
   }

   while ( intStack.pop( intValue ) )  
      cout << intValue << ' ';

   return 0;
}
7.7
Exception: Stack<>::top(): empty stack
7








13.16.generic stack
13.16.1.Generic Stack
13.16.2.A generic stack with size 10
13.16.3.template stack based on deque
13.16.4.Max size as the parameter for a generic stack
13.16.5.Generic stack based on vector
13.16.6.template string stack
13.16.7.Generic stack with deque
13.16.8.Use generic stack to store another container