Template Class in C++

Level 5337 keystrokes

A class template Stack<T> wraps a vector and works with any element type. Values pushed onto a Stack<int> come back out in reverse order (last in, first out): 20, then 10.

C++ code

// T is a type parameter, filled in when the template is used
1template<typename T>
2class Stack {
// Elements are stored in a vector; the back is the top of the stack
3 vector<T> data;
4public:
// push adds a value on top
5 void push(T value) { data.push_back(value); }
// pop reads the top value, removes it and returns it
6 T pop() { T top = data.back(); data.pop_back(); return top; }
// Whether the stack is empty
7 bool empty() const { return data.empty(); }
8};
9
// Instantiates the template with T = int
10Stack<int> intStack;
// Pushes 10, then 20
11intStack.push(10);
12intStack.push(20);
// Last in, first out: prints 20, then 10
13cout << intStack.pop() << endl;
14cout << intStack.pop() << endl;

Output

20
10
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • ;× 12
  • (× 11
  • )× 11
  • <× 11
  • .× 8
  • {× 4
  • }× 4
  • >× 3
  • _× 2
  • :× 1

More C++ examples at level 5

← C++ typing practice