#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