Stack类模板
#ifndef STACK_H
#define STACK_H
template <typename T>
class Stack
{
public:
Stack( int = 10 ); //defaultconstructor (Stack size 10)
// destructor
~Stack()
{
delete [] stackPtr; //deallocateinternal space for Stack
} // end ~Stack destructor
//determine whether Stack is full
bool isFull() const
{
return top == size - 1;
}
//determine whether Stack is empty
bool isEmpty() const
{
return top == -1;
}
bool push(constT&);// push an element onto the Stack
bool pop( T&); // popan element off the Stack
private:
int size; // # of elementsin the Stack
int top; // location of thetop element (-1 means empty)
T *stackPtr; // pointer to internal representation of the Stack
}; // end class template Stack
// constructor template
template <typename T>
Stack<T>::Stack( ints )
:size( s>0?s:0), // validatesize
top(-1), // Stack initiallyempty
stackPtr(new T[size]) // allocate memoryfor elements
{
// empty body
} // end Stack contructortemplate
//push element onto Stack
// if successful , return true;otherwise, return false
template <typename T>
bool Stack<T>::push(const T&pushValue)
{
if(!isFull())
{
stackPtr[++top]=pushValue;
return true;
}
return false;
}
// pop element off Stack
// if successful ,return true;otherwise,return false
template <typename T>
bool Stack<T>::pop(T&popValue)
{
if(!isEmpty())
{
popValue=stackPtr[top--];// remove item from Stack
return true; // pop successful
}
return false;
} // end function template pop
#endif
#include <iostream>
using namespace std;
#include "Stack.h"
int main()
{
Stack<double> doubleStack( 5 );// size 5
cout<<"Push elements onto doubleStack\n";
double doubleValue = 1.1;
while( doubleStack.push( doubleValue ))
{
cout<<doubleValue<<' ';
doubleValue +=1.1;
}
cout<<"\nStack isfull.Cannot push" << doubleValue
<< "\n\nPoping elementsfrom doubleValue\n";
while(doubleStack.pop( doubleValue ))
cout<<doubleValue<< ' ';
cout<<"\nStack isempty.Cannot pop\n";
return 0;
}