fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstdlib>
  4. #include <string>
  5. #include <stdexcept>
  6. using namespace std;
  7.  
  8. template <class T>
  9. class Stack {
  10. private:
  11. vector<T> element; // elements
  12.  
  13. public:
  14. void push(T const&); // push element
  15. void pop(); // pop element
  16. T top() const; // return top element
  17. bool empty() const{ // return true if empty.
  18. return element.empty();
  19. }
  20. };
  21.  
  22. template <class T>
  23. void Stack<T>::push (T const& item) {
  24. element.push_back(item);
  25. }
  26.  
  27. template <class T>
  28. void Stack<T>::pop () {
  29. if (element.empty()) {
  30. throw out_of_range("Stack<>::pop(): empty stack");
  31. }
  32. element.pop_back();
  33. }
  34.  
  35. template <class T>
  36. T Stack<T>::top () const
  37. {
  38. if (element.empty()) {
  39. throw out_of_range("Stack<>::top(): empty stack");
  40. }
  41. return element.back();
  42. }
  43.  
  44. int main()
  45. {
  46. try {
  47. Stack<int> myIntegerStack; // stack of ints
  48. Stack<string> myStringStack; // stack of strings
  49.  
  50. myIntegerStack.push(10);
  51. cout << myIntegerStack.top() <<endl;
  52.  
  53. myStringStack.push("Messi");
  54. cout << myStringStack.top() << std::endl;
  55. myStringStack.pop();
  56. }
  57. catch (exception const& ex) {
  58. cerr << "Exception: " << ex.what() <<endl;
  59. return -1;
  60. }
  61. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
10
Messi