home *** CD-ROM | disk | FTP | other *** search
- // \EXAMPLES\EX17011B.CPP - AStack.CPP
-
- //----------------------------------------------------------
- // Example of template container classes implenenting stacks.
- // This version includes templates but no exception handling.
- //----------------------------------------------------------
- //----------------------------------------------------------
- // Exception handling is supported only by
- // the IBM C++ Set/2 compiler
- // Templates are not supported by
- // the Microcoft Visual C++ compiler
- // Two versions of this program are included:
- // EX1701I.EXE - for IBM CSet II
- // EX1701B.EXE - for Borland Turbo C++
- //----------------------------------------------------------
- // Files in this example:
- // %F,15,EX17010B.H%EX17010B.H Stack.H base class stack
- // %F,15,EX17011B.H%EX17011B.H AStack.H derived array stack
- // EX17011B.CPP this file -- AStack.CPP
- // %F,15,EX17012B.H%EX17012B.H LLStack.H derived linked list stack
- // %F,15,EX17012B.CPP%EX17012B.CPP LLStack.CPP
- // %F,15,EX17013B.H%EX17013B.H Exception.H
- // %F,15,EX17014B.H%EX17014B.H Iterator.H iterator class
- // %F,15,EX1701B.CPP%EX1701B.CPP main() without exception handling
- // %F,15,EX1701.CPP%EX1701.CPP main() with exception handling
- //----------------------------------------------------------
- #include <stdlib.h>
-
- #ifndef INCL_EX17011_CPP
- #define INCL_EX17011_CPP
-
- #include "EX17010B.H"
- #include "EX17011B.H"
-
- template<class T>
- AStack<T>::AStack( unsigned long capacity)
- : size (0), free(0), pArray( (T *)NULL)
- {
- pArray = new T[capacity]; // allocate array to store data
- if ( pArray == (T *)NULL)
- {
- cout << "Memory allocation error: Aborting." << endl;
- abort(); // aborts if memory error
- }
- size = free = capacity; // initialize size and free;
- }
-
-
- template<class T>
- AStack<T>::~AStack()
- {
- delete[] pArray; // deallocate the array
- }
-
-
- template<class T> void
- AStack<T>::Push( const T y)
- {
- if ( Full())
- {
- cout << "Stack Full: Aborting." << endl;
- abort(); // abort if full
- }
- pArray[size -free] = y; // store data a next pos
- free--; // decrement the number of free elements
- }
-
-
- template<class T> T
- AStack<T>::Pop()
- {
- if ( Empty())
- {
- cout << "Stack Empty: Aborting." << endl;
- abort(); // abort if empty
- }
- // return top element and remove element from stack
- return pArray[(size - free++) - 1];
- }
-
-
-
- template<class T> T
- AStack<T>::OnTop() const
- {
- if (Empty())
- {
- cout << "Stack Empty: Aborting." << endl;
- abort(); // abort if empty
- }
-
- // return top element of stack
- return pArray[size - free - 1];
- }
-
- #endif
-