Start learning free

LESSON 65 OF 69 · PROJECTS: OBJECT-ORIENTED

Stack Implementation in C++: Build a MyStack Class

Practice Read the full explanation

A stack is a pile where you only touch the top: the last value you put in is the first one you take out (LIFO, last in, first out), like a pile of plates. Build a class MyStack that stores whole numbers in a private vector<int> data and offers four operations.

The methods:

  • void push(int value)
  • int pop()
  • int peek()
  • int size()

Rules:

  • push puts the value on top of the stack. It returns nothing.
  • pop removes the top value (the one pushed last) and returns it.
  • peek returns the top value but leaves it on the stack, so the size does not change.
  • size returns how many values are on the stack. A new stack has size 0, and after popping everything the size is 0 again.
  • The stack keeps working after it becomes empty: you can push again.
  • Calling pop or peek on an empty stack is not part of this exercise and the tests never do it. (In C++, back() on an empty vector is undefined behaviour.)

You start with: The starter already contains the code that uses your stack (below).

MyStack s;
s.push(10);
s.push(20);
s.push(30);
cout << "Top: " << s.peek() << endl;
cout << "Size: " << s.size() << endl;
cout << "Pop: " << s.pop() << endl;
cout << "Size: " << s.size() << endl;
cout << "Pop: " << s.pop() << endl;
cout << "Pop: " << s.pop() << endl;
cout << "Empty size: " << s.size() << endl;
s.push(7);
cout << "Top: " << s.peek() << endl;
cout << "Size: " << s.size() << endl;

Expected output:

Top: 30
Size: 3
Pop: 30
Size: 2
Pop: 20
Pop: 10
Empty size: 0
Top: 7
Size: 1

Reading the output: after pushing 10, 20 and 30 the top is 30 and the size 3. Popping gives 30, leaving size 2. Two more pops give 20 and then 10 (last in, first out), the stack is empty (size 0), and after pushing 7 the top is 7 and the size 1.


The top of the stack is the end of the list: adding and removing at the end is fast, and the last value pushed is always the last element.

vector has push_back, back() and pop_back(). pop_back() returns nothing, so save data.back() in a variable first, then remove it, then return the variable.

class MyStack {
private:
    vector<int> data;
public:
    void push(int value) {
        data.push_back(value);
    }

    int pop() {
        int top = data.back();
        data.pop_back();
        return top;
    }

    int peek() {
        return data.back();
    }

    int size() {
        return data.size();
    }
};

STEP 1 OF 13
    Ctrl + Enter to check

    C++ · PROJECTS: OBJECT-ORIENTED

    Stack Impl in C++, explained

    Problem overview

    A stack is a pile where you only touch the top. The last value you put in is the first one you take out, which is called LIFO (last in, first out). The lesson asks for a class MyStack that stores whole numbers in a private vector<int> data and offers four operations:

    • void push(int value) puts a value on top and returns nothing.
    • int pop() removes the top value and returns it.
    • int peek() returns the top value and leaves it on the stack.
    • int size() returns how many values the stack holds.

    The code at the bottom of the starter pushes 10, 20 and 30, then inspects and pops. After the three pushes the top is 30 and the size is 3. The first pop returns 30 and leaves size 2. Two more pops return 20 and then 10, so the values come back in the reverse of the order they went in. The stack is now empty, and it keeps working: pushing 7 gives a top of 7 and a size of 1. The output:

    Top: 30
    Size: 3
    Pop: 30
    Size: 2
    Pop: 20
    Pop: 10
    Empty size: 0
    Top: 7
    Size: 1

    Popping or peeking at an empty stack is not part of the exercise, and the lesson's tests never do it.

    Approach: the end of the vector is the top

    A vector is a resizable array, and it is fast to add and remove at its end. If the end of the vector is the top of the stack, each operation maps to one vector operation:

    Stack operationVector call
    pushpush_back(value)
    peekback()
    popback(), then pop_back()
    sizesize()

    Using the front of the vector as the top would also work, but every push and pop would have to shift all the other elements. The end needs no shifting.

    pop needs a little care. In C++, pop_back() removes the last element and returns nothing, and once the element is gone you can't read it. So pop must save the value first, remove it, and then return the saved copy.

    Step by step

    1. Declare MyStack and write its closing }; immediately, because a class ends with a semicolon.
    2. Add the private field. Under private:, declare vector<int> data;. Only the class's own methods can touch it, so outside code can't reorder or edit the stored values.
    3. Open a public: section for the methods the driver calls.
    4. Start push as a void method taking an int named value.
    5. Append the value with data.push_back(value). The newest value is now last, which makes it the top.
    6. Start pop as a method returning int. Its body has three lines.
    7. Save the top in an int named top, using data.back().
    8. Remove the last element with data.pop_back(). This is why the value was saved first.
    9. Return top, the value the caller asked for.
    10. Start peek as a method returning int.
    11. Return data.back(). It only reads the last element, so the stack is unchanged and the size stays the same.
    12. Start size as a method returning int.
    13. Return data.size(): one vector element per stored value, so the vector's size is the stack's size.

    The solution in C++

    class MyStack {
    private:
        vector<int> data;
    public:
        void push(int value) {
            data.push_back(value);
        }
    
        int pop() {
            int top = data.back();
            data.pop_back();
            return top;
        }
    
        int peek() {
            return data.back();
        }
    
        int size() {
            return data.size();
        }
    };
    
    class Solution {
    public:
        void mainFunction() {
            MyStack s;
            s.push(10);
            s.push(20);
            s.push(30);
            cout << "Top: " << s.peek() << endl;
            cout << "Size: " << s.size() << endl;
            cout << "Pop: " << s.pop() << endl;
            cout << "Size: " << s.size() << endl;
            cout << "Pop: " << s.pop() << endl;
            cout << "Pop: " << s.pop() << endl;
            cout << "Empty size: " << s.size() << endl;
            s.push(7);
            cout << "Top: " << s.peek() << endl;
            cout << "Size: " << s.size() << endl;
        }
    };
    

    C++ details worth knowing

    • back() versus pop_back(). back() gives access to the last element and removes nothing; pop_back() removes it and gives nothing back. Combining them is how pop returns the value and removes it.
    • size() converts an unsigned value. data.size() has an unsigned type, size_t, and the method returns int, so the value is converted. For the small stacks in this lesson that is harmless. Be careful with expressions such as data.size() - 1 on an empty vector: unsigned arithmetic wraps around. For an empty vector<int> that expression gives 18446744073709551615, not -1.
    • Empty stacks are undefined behaviour. Calling back() or pop_back() on an empty vector doesn't throw an error; the behaviour is undefined. That is why the statement promises the tests never do it. A stack you ship would check size() == 0 first.
    • Private data. data is hidden, so the class is free to change how it stores values without breaking the code that uses it.

    Complexity

    All four operations take constant time on average. push_back is amortised O(1): usually it writes into spare capacity, and occasionally the vector grows and copies its elements, which averages out. back(), pop_back() and size() are O(1). The stack uses O(n) space for the n values it holds.

    Edge cases and common mistakes

    • Returning without saving. Calling pop_back() and then trying to return data.back() returns the wrong element, the new top, not the removed one. Save the value first.
    • Making peek remove the value. peek must only read, or the size changes and later pops return the wrong numbers.
    • Treating the front as the top. The order of results would be wrong, or each operation would be slower.
    • Reusing the stack after it empties. Nothing special is needed: pushing onto an empty stack works, as the driver's last lines show.

    Testing

    Push 1, 2, 3 and 4 into a new stack. Calling peek() twice gives 4 both times and the size is still 4. Popping until the size is 0 returns the values in the reverse order:

    4 3 2 1

    Key takeaways

    • A stack is last in, first out, and the end of a vector is a natural top.
    • pop_back() returns nothing, so save back() before removing it.
    • Keep the vector private and expose only the four operations.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free