Learn C++
#include "stlcontainers/stack_queue.hpp"

stack, queue & priority_queue in C++

//concept

These container adapters restrict an underlying container (deque by default) to one discipline: stack is LIFO (push/pop/top), queue is FIFO (push/pop/front), and priority_queue always serves the largest element first (push/pop/top on a heap). The restriction is the feature — algorithms declare their access pattern and the type system enforces it.

All operations are O(1) amortized except priority_queue's O(log n) push/pop. Adapters expose no iterators: if you need to traverse, you picked the wrong tool (or peek by popping into a scratch copy).

//how it works
1

stack: last in, first out

push adds, top peeks, pop removes — parentheses matching, undo, and DFS all speak stack.

2

queue: first in, first out

push enqueues at the back, front peeks, pop dequeues — BFS and task pipelines speak queue.

3

priority_queue: biggest first

A max-heap by default: top() is always the current maximum, with O(log n) push/pop. Add greater<T> for a min-heap.

4

No iteration by design

Adapters hide iterators deliberately — traversal would violate the discipline they exist to enforce.

//example
#include <iostream>
#include <stack>
#include <queue>
 
int main() {
std::stack<int> s;
s.push(1);
s.push(2);
std::queue<int> q;
q.push(1);
q.push(2);
std::cout << s.top() << ", " << q.front() << std::endl;
return 0;
}
Output
2, 1
1The stack holds [1, 2] with 2 on top — LIFO serves the most recent first.
2The queue holds [1, 2] with 1 at front — FIFO serves the oldest first.
32, 1 prints — same insertions, opposite serving orders.
//use cases
Bracket matching, expression evaluation, and DFS with stack
BFS frontiers and producer-consumer pipelines with queue
Top-k, scheduling, and Dijkstra frontiers with priority_queue
Swapping the underlying container (vector for stack) when profiling demands

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.