C++: A stack class

Wrap a vector in a class with a clear interface.

What to build

A class that exposes only what a stack should do.

Requirements

  • Write a class Stack with push(int), bool pop(int& out), int size() const and bool empty() const.
  • pop returns false if the stack is empty.
  • push X prints nothing. pop prints the value or empty. size prints the size.

Input

The first line has n. Each of the next n lines is a command.

Output

One line for each pop and size.

Constraints

n is from 1 to 1000.

Example

Input:

4
push 3
push 7
pop
size

Output:

7
1

Why it works

Callers can only use the four methods, so the data cannot be damaged, and the inside could later be replaced without changing any code that uses it.

Examples

Example 1 · Input
4
push 3
push 7
pop
size
Expected output
7
1
Example 2 · Input
2
pop
size
Expected output
empty
0

Hints

Hint 1

Keep a private vector<int>.

Hint 2

Have pop return a bool, and give the value through a reference.

Hint 3

empty() and size() can be const.

Solution

Show one correct solution (try it yourself first)
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Stack {
    vector<int> items;

public:
    void push(int x) { items.push_back(x); }
    bool pop(int& out) {
        if (items.empty()) return false;
        out = items.back();
        items.pop_back();
        return true;
    }
    int size() const { return static_cast<int>(items.size()); }
    bool empty() const { return items.empty(); }
};

int main() {
    int n;
    cin >> n;
    Stack s;
    for (int i = 0; i < n; i++) {
        string command;
        cin >> command;
        if (command == "push") {
            int x;
            cin >> x;
            s.push(x);
        } else if (command == "pop") {
            int value;
            if (s.pop(value)) cout << value << endl;
            else cout << "empty" << endl;
        } else {
            cout << s.size() << endl;
        }
    }
    return 0;
}

Lesson: Structs and your first class →