• Source
    1. #include <iostream>
    2. #include <vector>
    3. #include <cstdlib>
    4. #include <string>
    5. #include <stdexcept>
    6.  
    7. using namespace std;
    8.  
    9. template <class T>
    10. class Stack
    11. {
    12. private:
    13. vector<T> elements;
    14.  
    15. public:
    16. void push(T const &);
    17. void pop();
    18. T top();
    19. bool empty();
    20. };
    21.  
    22. template <class T>
    23. void Stack<T>::push(T const &elem) {
    24. elements.push_back(elem);
    25. }
    26.  
    27. template <class T>
    28. void Stack<T>::pop() {
    29. if (elements.empty()) {
    30. throw out_of_range("Stack<>::pop(): empty stack");
    31. } else {
    32. elements.pop_back();
    33. }
    34. }
    35.  
    36. template <class T>
    37. T Stack<T>::top() {
    38. if (empty()) {
    39. throw out_of_range("Stack<>::top(): empty stack");
    40. }
    41. return elements.back();
    42. }
    43.  
    44. template <class T>
    45. bool Stack<T>::empty() {
    46. return elements.empty();
    47. }
    48.  
    49.  
    50. int main() {
    51. try {
    52. Stack<int> intStack; // stack of ints
    53. Stack<string> stringStack; // stack of strings
    54.  
    55. // manipulate integer stack
    56. intStack.push(7);
    57. cout << intStack.top() << endl;
    58.  
    59. // manipulate string stack
    60. stringStack.push("hello");
    61. cout << stringStack.top() << std::endl;
    62. stringStack.pop();
    63. stringStack.pop();
    64. }
    65. catch (exception const &ex) {
    66. cerr << "Exception: " << ex.what() << endl;
    67. return -1;
    68. }
    69. }