template class ArrayStack { private: T *data, // pointer to dynamically allocated array of "T" capacity; // capacity of stack, size of array bool elastic; // true if capacity of stack (i.e. the size of the array) // can be changed as required. int count; // number of values on stack public: // creates an "elastic" stack ArrayStack (); // creates a stack with a fixed capacity ArrayStack (int capacity); ArrayStack (const ArrayStack &otherStack); ~ArrayStack (); // throws an "overflow_error" exception if the stack has a fixed // capacity and is full. void push (T value); // throws an "overflow_error" exception if the stack is empty T pop (); // returns top value without removing it // throws an "overflow_error" exception if the stack is empty T peek(); bool isEmpty() const { return count == 0; } int getcount() const { return count; } // copies contents only (capacity attributes are not copied). // throws an "overflow_error" exception if the destination stack // has a fixed capacity and this is not large enough. ArrayStack& operator= (const ArrayStack &otherStack); }; static const int initialCapacity = 10, capacityIncrement = 5; template ArrayStack::ArrayStack () { data = new T[initialCapacity]; capacity = initialCapacity; elastic = true; count = 0; } template ArrayStack::ArrayStack (int capacity) { if (capacity <= 0) { throw invalid_argument ("ArrayStack::ArrayStack - invalid capacity"); } data = new T[capacity]; this -> capacity = capacity; elastic = false; count = 0; } template ArrayStack::ArrayStack (const ArrayStack &otherStack) { data = new T[otherStack.capacity]; capacity = otherStack.capacity; elastic = otherStack.elastic; count = otherStack.count; for (int i = 0; i < count; i++) { data[i] = otherStack.data[i]; } } template ArrayStack::~ArrayStack () { delete [] data; } template void ArrayStack::push (T value) { int i; T *temp; if (elastic && (count == capacity)) { // time to increase the capacity capacity += capacityIncrement; temp = new T[capacity]; for (i = 0; i < count; i++) temp[i] = data[i]; delete [] data; data = temp; } else if (count == capacity) { throw overflow_error ("ArrayStack::push - stack overflow"); } data[count++] = value; } template T ArrayStack::pop () { if (count == 0) { throw overflow_error ("ArrayStack::pop - stack underflow"); } return data[--count]; } template T ArrayStack::peek () { if (count == 0) { throw overflow_error ("ArrayStack::peek - stack underflow"); } return data[count-1]; } template ArrayStack& ArrayStack::operator= (const ArrayStack &otherStack) { if (capacity < otherStack.count) { if (!elastic) { throw overflow_error ("ArrayStack - copy overflow"); } delete [] data; data = new T[otherStack.count]; capacity = otherStack.count; } for (int i = 0; i < otherStack.count; i++) { data[i] = otherStack.data[i]; } count = otherStack.count; return *this; }