C++ stack, queue & priority_queue: Container Adapters & BFS/DFS
이 글의 핵심
Compare stack, queue, and priority_queue with examples for graph traversal and scheduling.
For stacks and queues as abstract types and how they show up in BFS/DFS, see stacks and queues.
Comparison
| Feature | stack | queue | priority_queue |
|---|---|---|---|
| Order | LIFO | FIFO | Priority (heap) |
| Access | top() | front(), back() | top() |
| Push | push() | push() | push() |
| Pop | pop() | pop() | pop() |
stack
push, top, pop, size, empty — no random access.
queue
push, front, back, pop.
priority_queue
Default max-heap; priority_queue<T, vector<T>, greater<T>> for min-heap.
Examples
- DFS with explicit stack (iterative).
- BFS with queue storing
{node, distance}for shortest path in unweighted graphs. - Task scheduling with
priority_queueand customoperator<or comparator struct.
Common pitfalls
- No
operator[]on stack/queue — drain or use deque/vector if index access is required. pop()returns void — readtop()/front()first.- Custom types in
priority_queueneedoperator<or explicit comparator type.
FAQ
When to use each adapter; deque for double-ended work; min-heap with greater; dynamic sizing vs fixed arrays; O(1) vs O(log n) for priority_queue; thread safety requires external locking.
Related posts
- C++ container adapters
- C++ data structures from scratch
- C++ stack overflow (concept)
Keywords
std::stack, std::queue, priority_queue, BFS, DFS, LIFO, FIFO, heap, STL