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 used1template<typename T>2class Stack { // Elements are stored in a vector; the back is the top of the stack3 vector<T> data;4public: // push adds a value on top5 void push(T value) { data.push_back(value); } // pop reads the top value, removes it and returns it6 T pop() { T top = data.back(); data.pop_back(); return top; } // Whether the stack is empty7 bool empty() const { return data.empty(); }8};9 // Instantiates the template with T = int10Stack<int> intStack;// Pushes 10, then 2011intStack.push(10);12intStack.push(20);// Last in, first out: prints 20, then 1013cout << intStack.pop() << endl;14cout << intStack.pop() << endl;Output
20 10
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