Skip to content
  • stack, queue & priority_queue · C++

stack, queue & priority_queue

LearnViaNotes @learnvianotes· 2 min read

Container adaptors wrap a sequence container and expose only a restricted interface: LIFO (stack), FIFO (queue) or “largest first” (priority_queue).

std::stack & std::queue

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

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

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

    std::queue<std::string> q;                  // FIFO
    q.push("first"); q.push("second"); q.push("third");
    q.pop();
    std::cout << q.front() << ' ' << q.back() << ' ' << q.size() << '\n';
}
Output
10
second third 2
AdaptorOperationsDefault underlying container
stack<T>push, pop, top, empty, sizedeque<T>
queue<T>push, pop, front, back, empty, sizedeque<T>
priority_queue<T>push, pop, top, empty, sizevector<T> (binary heap)

std::priority_queue

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

int main() {
    std::priority_queue<int> maxHeap;                                   // largest on top
    for (int x : {3, 1, 4, 1, 5}) maxHeap.push(x);
    std::cout << maxHeap.top() << ' ';
    maxHeap.pop();
    std::cout << maxHeap.top() << '\n';

    std::priority_queue<int, std::vector<int>, std::greater<int>> minHeap{std::greater<int>(), {3, 1, 4}};
    std::cout << minHeap.top() << '\n';                                 // smallest on top

    using Task = std::pair<int, std::string>;                           // (priority, name)
    auto cmp = [](const Task& a, const Task& b) { return a.first > b.first; };   // lower number = more urgent
    std::priority_queue<Task, std::vector<Task>, decltype(cmp)> tasks(cmp);
    tasks.push({2, "email"}); tasks.push({1, "outage"}); tasks.push({3, "lunch"});
    while (!tasks.empty()) { std::cout << tasks.top().second << ' '; tasks.pop(); }
    std::cout << '\n';
}
Output
5 4
1
outage email lunch

Top-k with a heap

C++
#include <functional>
#include <iostream>
#include <queue>
#include <vector>
int main() {
    std::vector<int> scores{50, 90, 20, 70, 85, 60};
    std::priority_queue<int, std::vector<int>, std::greater<int>> top3;   // min-heap of size k
    for (int s : scores) {
        top3.push(s);
        if (top3.size() > 3) top3.pop();       // drop the smallest: O(n log k)
    }
    while (!top3.empty()) { std::cout << top3.top() << ' '; top3.pop(); }
    std::cout << '\n';
}
Output
70 85 90

How is priority_queue implemented?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report