stack, queue & priority_queue in C++
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).
stack: last in, first out
push adds, top peeks, pop removes — parentheses matching, undo, and DFS all speak stack.
queue: first in, first out
push enqueues at the back, front peeks, pop dequeues — BFS and task pipelines speak queue.
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.
No iteration by design
Adapters hide iterators deliberately — traversal would violate the discipline they exist to enforce.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.