Stack Class

Lab C++ Intermediate 20 points

Implement class IntStack on top of a vector with push, pop (returns bool, false when empty), top, size and empty. Process commands.

Input

n, then commands push X, pop, top, size.

Output

Output of pop failures, top and size.

Example

Input

7
push 1
push 2
top
pop
top
size
pop

Output

2
1
1
Sample input available Sample output available
Editor
C++

Hints

Reporting failure with a bool return value works without exceptions.

Solution explanation

The class hides the vector and exposes only stack operations.

Show solution
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class IntStack {
public:
    void push(int x) { data_.push_back(x); }
    bool pop() {
        if (data_.empty()) return false;
        data_.pop_back();
        return true;
    }
    int top() const { return data_.back(); }
    size_t size() const { return data_.size(); }
    bool empty() const { return data_.empty(); }

private:
    vector<int> data_;
};

int main() {
    IntStack s;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        string cmd;
        cin >> cmd;
        if (cmd == "push") {
            int x;
            cin >> x;
            s.push(x);
        } else if (cmd == "pop") {
            if (!s.pop()) cout << "empty\n";
        } else if (cmd == "top") {
            if (s.empty()) cout << "empty\n";
            else cout << s.top() << "\n";
        } else {
            cout << s.size() << "\n";
        }
    }
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD