1#include <iostream>
2#include <vector>
3#include <cstdlib>
4#include <string>
5#include <stdexcept>
6
7using namespace std;
8
9template <class T>
10class Stack {
11 private:
12 vector<T> elems; // elements
13
14 public:
15 void push(T const&); // push element
16 void pop(); // pop element
17 T top() const; // return top element
18
19 bool empty() const { // return true if empty.
20 return elems.empty();
21 }
22};
23
24template <class T>
25void Stack<T>::push (T const& elem) {
26 // append copy of passed element
27 elems.push_back(elem);
28}
29
30template <class T>
31void Stack<T>::pop () {
32 if (elems.empty()) {
33 throw out_of_range("Stack<>::pop(): empty stack");
34 }
35
36 // remove last element
37 elems.pop_back();
38}
39
40template <class T>
41T Stack<T>::top () const {
42 if (elems.empty()) {
43 throw out_of_range("Stack<>::top(): empty stack");
44 }
45
46 // return copy of last element
47 return elems.back();
48}
49
50int main() {
51 try {
52 Stack<int> intStack; // stack of ints
53 Stack<string> stringStack; // stack of strings
54
55 // manipulate int 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 } catch (exception const& ex) {
65 cerr << "Exception: " << ex.what() <<endl;
66 return -1;
67 }
68}
1#include <iostream>
2#include <string>
3
4using namespace std;
5
6template <typename T>
7inline T const& Max (T const& a, T const& b) {
8 return a < b ? b:a;
9}
10
11int main () {
12 int i = 39;
13 int j = 20;
14 cout << "Max(i, j): " << Max(i, j) << endl;
15
16 double f1 = 13.5;
17 double f2 = 20.7;
18 cout << "Max(f1, f2): " << Max(f1, f2) << endl;
19
20 string s1 = "Hello";
21 string s2 = "World";
22 cout << "Max(s1, s2): " << Max(s1, s2) << endl;
23
24 return 0;
25}