#include <iostream> #include <stdexcept> #include <cstdlib> #include <string> using namespace std; template <class T> class Stack { private: T *stk; int size, tos, maxsize; public: Stack(int); ~Stack() {delete [] stk;} T top() const; void pop(); void push(T); template <class sT> friend ostream& operator<<(ostream &, const Stack<sT> &); bool isempty() const { return (size == 0); } }; template <class T> Stack<T>::Stack(int s) { size = 0; maxsize = s; tos = -1; if (s <= 0) { throw out_of_range("stack(): size cant be zero or nagative."); } else { stk = new T[maxsize]; } } template <class sT> ostream& operator<<(ostream &out, const Stack<sT> &s) { int i; cout << '['; for (i = 0; i < s.size; i++) { out << s.stk[i] << "," << ends; } cout << "\b\b"; cout << ']'; return out; } template <class T> T Stack<T>::top() const { if (isempty()) { throw out_of_range("top() error: stack is empty."); } else { return stk[tos]; } } template <class T> void Stack<T>::push(T elem) { if(size == maxsize) { throw out_of_range("push error: Stack is full."); } else { stk[++tos] = elem; ++size; } } template <class T> void Stack<T>::pop() { if(isempty()) { throw out_of_range("pop() error: Stack is full."); } else { size--; tos--; } } int main() { try { cout << "<For Integers>" << endl; Stack<int> s(5); s.push(1); s.push(2); s.push(3); s.push(4); cout << "Stack:" << s << endl; cout << "\n<For Strings>" << endl; Stack<string> g(4); g.push("Superman"); g.push("Batman"); g.push("Flash"); g.push("Spiderman"); cout << "Stack:["; while(!g.isempty()) { cout << g.top() << "," << ends; g.pop(); } cout << "\b\b]" << endl; cout << "\n<Exception>" << endl; Stack<int> j(0); } catch(exception &e) { cerr << e.what() << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
<For Integers> Stack:[1, 2, 3, 4] <For Strings> Stack:[Spiderman, Flash, Batman, Superman] <Exception> stack(): size cant be zero or nagative. -------------------------------- Process exited after 0.3268 seconds with return value 1 Press any key to continue . . .