C++ · Module 13 · Lesson 51 min read

Container Adaptors: stack, queue, priority_queue

What is an adaptor?

A wrapper around another container (by default deque or vector) that exposes only the operations that make sense. No iteration, no random access.

std::stack<T> — LIFO (last in, first out)

OperationMeaning
push(x) / emplace(...)add on top
top()look at the top
pop()remove the top (returns void!)
size(), empty()
Uses: undo/redo, bracket matching, expression evaluation, DFS, browser back button.

std::queue<T> — FIFO (first in, first out)

push(x) at the back, front(), back(), pop() from the front. Uses: task queues, BFS, print jobs, customer service lines, message buffers.

std::priority_queue<T> — highest priority first

  • push, top, pop; top() is always the largest element (max-heap)
  • Min-heap: std::priority_queue<int, std::vector<int>, std::greater<int>>
  • Custom priority: pass a comparator (lambda with decltype)
  • O(log n) push/pop, O(1) top Uses: scheduling, Dijkstra's shortest path, "top K" problems, event simulation, merging sorted lists.

Why pop() returns void

For exception safety: if copying the returned element threw, the element would be lost. So you call top() then pop().

⚠️ Calling top()/front()/pop() on an empty adaptor

Undefined behaviour — always check empty() first.

Underlying container

std::stack<int, std::vector<int>> s; — choose a different backing container if you want.

Example

C++
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <vector>

bool balanced(const std::string& expr) {
    std::stack<char> open;
    for (char c : expr) {
        if (c == '(' || c == '[' || c == '{') open.push(c);
        else if (c == ')' || c == ']' || c == '}') {
            if (open.empty()) return false;
            char o = open.top();
            open.pop();
            if ((c == ')' && o != '(') || (c == ']' && o != '[') || (c == '}' && o != '{')) return false;
        }
    }
    return open.empty();
}

struct Task {
    std::string name;
    int priority;
};

int main() {
    std::stack<std::string> undo;
    for (const char* action : { "add expense", "edit amount", "delete note" }) undo.push(action);
    std::cout << "undo order:";
    while (!undo.empty()) { std::cout << " [" << undo.top() << "]"; undo.pop(); }
    std::cout << '\n';

    std::cout << std::boolalpha << "balanced(\"{[()()]}\") = " << balanced("{[()()]}")
              << ", balanced(\"([)]\") = " << balanced("([)]") << '\n';

    std::queue<std::string> sync_jobs;
    sync_jobs.push("upload receipts");
    sync_jobs.push("backup database");
    sync_jobs.push("send report");
    std::cout << "processing in arrival order:";
    while (!sync_jobs.empty()) { std::cout << " [" << sync_jobs.front() << "]"; sync_jobs.pop(); }
    std::cout << '\n';

    std::priority_queue<int> max_heap;
    for (int x : { 300, 1500, 800, 15000, 450 }) max_heap.push(x);
    std::cout << "top 3 expenses:";
    for (int i = 0; i < 3; ++i) { std::cout << ' ' << max_heap.top(); max_heap.pop(); }
    std::cout << '\n';

    std::priority_queue<int, std::vector<int>, std::greater<int>> min_heap;
    for (int x : { 5, 1, 4, 2 }) min_heap.push(x);
    std::cout << "smallest first:";
    while (!min_heap.empty()) { std::cout << ' ' << min_heap.top(); min_heap.pop(); }
    std::cout << '\n';

    auto lower_priority = [](const Task& a, const Task& b) { return a.priority < b.priority; };
    std::priority_queue<Task, std::vector<Task>, decltype(lower_priority)> todo(lower_priority);
    todo.push({ "pay rent", 10 });
    todo.push({ "buy snacks", 1 });
    todo.push({ "renew insurance", 7 });
    std::cout << "most urgent: " << todo.top().name << '\n';
    return 0;
}

/* Output:
undo order: [delete note] [edit amount] [add expense]
balanced("{[()()]}") = true, balanced("([)]") = false
processing in arrival order: [upload receipts] [backup database] [send report]
top 3 expenses: 15000 1500 800
smallest first: 1 2 4 5
most urgent: pay rent
*/