Write a class template Stack<T> with push, pop (returns the top item and removes it), empty and size. main uses a Stack<string> to handle these commands:
push WORD: put the word on top.pop: print the top word and remove it, oremptyif there is none.size: print how many words there are.
What to build
A class template Stack<T> used as a stack of words.
Requirements
- Store the items in a
vector<T>. - Write
push,pop,emptyandsize. - Print
emptywhen a pop is asked of an empty stack.
Input
The first line has q (1 ≤ q ≤ 1000). Each of the next q lines has one command.
Output
One line for each pop and size.
Constraints
1 ≤ q ≤ 1000, and words have no spaces.
Example
Input:
5
push hello
push world
pop
size
pop
Output:
world
1
hello
Why it works
The stack's code does not depend on the item type, so one template gives a stack of strings here and a stack of anything else elsewhere.
Examples
Example 1 · Input
5 push hello push world pop size pop
Expected output
world 1 hello
Example 2 · Input
2 pop size
Expected output
empty 0
Hints
Hint 1
template <typename T> class Stack with a vector<T> items; member.
Hint 2
push: items.push_back(x); pop: take items.back(), then items.pop_back().
Hint 3
main uses Stack<string>.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template <typename T>
class Stack {
vector<T> items;
public:
void push(const T& x) { items.push_back(x); }
T pop() {
T top = items.back();
items.pop_back();
return top;
}
bool empty() const { return items.empty(); }
int size() const { return items.size(); }
};
int main() {
Stack<string> st;
int q;
cin >> q;
for (int i = 0; i < q; i++) {
string cmd;
cin >> cmd;
if (cmd == "push") {
string w;
cin >> w;
st.push(w);
} else if (cmd == "pop") {
if (st.empty()) cout << "empty" << endl;
else cout << st.pop() << endl;
} else {
cout << st.size() << endl;
}
}
return 0;
}