Generic stack : Your stack « Data Types « C++ Tutorial






#include <iostream>


using std::cout;
using std::cin;
using std::endl;

template< class T >
class Stack {
public:
   Stack( int = 10 );    
   ~Stack() { delete [] stackPtr; } 
   bool push( const T& ); 
   bool pop( T& );        
private:
   int size;             
   int top;              
   T *stackPtr;          

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

template< class T >
Stack< T >::Stack( int s )
{
   size = s > 0 ? s : 10;  
   top = -1;               
   stackPtr = new T[ size ]; 
}
template< class T >
bool Stack< T >::push( const T &pushValue )
{
   if ( !isFull() ) {
      stackPtr[ ++top ] = pushValue; 
      return true;  
   } 
   return false;     
}

template< class T > 
bool Stack< T >::pop( T &popValue )
{
   if ( !isEmpty() ) {
      popValue = stackPtr[ top-- ]; 
      return true;  
   } 
   return false;    
} 


int main()
{
   Stack< double > doubleStack( 5 );
   double f = 1.1;
   cout << "Pushing elements onto doubleStack\n";

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

   cout << f;

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

   Stack< int > intStack;
   int i = 1;

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

   cout << i ;

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

   return 0;

}








2.41.Your stack
2.41.1.Declare your own class stack
2.41.2.Generic stack
2.41.3.generic stack implementation
2.41.4.a stack as a class
2.41.5.Stack implementation with constructor