Codiqo

Learn C++ · lesson 61 of 61 · about 12 minutes

Project: A Generic Stack

Build a reusable stack class template and use it for numbers and for text.

What you'll learn

  • Design a class template's interface
  • Store items in a std::vector<T> inside it
  • Report errors with exceptions

The rune lock and the way home

The last door of the castle has a rune lock. The player types its runes as one word, like ([{}]), and the lock opens only if every rune that opens is closed by its own partner, in the right order: The rune lock opens, or The rune lock stays shut. Then the hero walks home through the places in the journal, last place first: The way home: castle, bridge, cave. The reading of the runes is written for you. Both jobs need a stack, one of characters and one of strings, so the project is one Stack<T> class template.

The plan

A stack is a pile: you add to the top and take from the top, last in, first out. The Stack<T> class will:

1. Keep its items in a private std::vector<T>
2. Offer push(x), pop(), top(), size() and empty()
3. Throw a std::runtime_error if you pop or look at an empty stack
4. Work for any type: we'll use it for brackets and for numbers

The class template

#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

template <typename T>
class Stack {
public:
    void push(const T& x) { items_.push_back(x); }
    T pop() {
        if (items_.empty()) throw std::runtime_error("pop from empty stack");
        T x = items_.back();
        items_.pop_back();
        return x;
    }
    std::size_t size() const { return items_.size(); }

private:
    std::vector<T> items_;
};

int main() {
    Stack<std::string> s;
    s.push("first");
    s.push("second");
    std::cout << s.pop() << " " << s.size() << "\n";
    try {
        s.pop();
        s.pop();
    } catch (const std::runtime_error& e) {
        std::cout << "Error: " << e.what() << "\n";
    }
}

Output

second 1
Error: pop from empty stack

Using it: balanced brackets

Stacks are perfect for checking brackets. Push every opening bracket; on a closing bracket, the top of the stack must be its partner. At the end, the stack must be empty.

Checking brackets

#include <iostream>
#include <string>
#include <vector>

bool balanced(const std::string& s) {
    std::vector<char> stack;
    for (char c : s) {
        if (c == '(' || c == '[') stack.push_back(c);
        else if (c == ')' || c == ']') {
            char want = c == ')' ? '(' : '[';
            if (stack.empty() || stack.back() != want) return false;
            stack.pop_back();
        }
    }
    return stack.empty();
}

int main() {
    std::cout << balanced("(a[b]c)") << balanced("(]") << balanced("((") << "\n";
}

Output

100

Two stacks from one template

Stack<char> runeStack holds the runes that are still open: (, [ and { are pushed, and ), ] and } pop the top, which has to be the partner. A closing rune when nothing is open makes pop() throw, and the catch turns that into a shut lock, as does anything still open at the end. Stack<std::string> wayBack has every place in the journal pushed onto it, and popping until it's empty gives them back last first.

Tip

Taking parameters as const T& avoids copying big items like strings, while still working for small ones like int.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.