C++ stack, queue & priority_queue: Container Adapters & BFS/DFS

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

Featurestackqueuepriority_queue
OrderLIFOFIFOPriority (heap)
Accesstop()front(), back()top()
Pushpush()push()push()
Poppop()pop()pop()

stack

push, top, pop, size, emptyno random access.


queue

push, front, back, pop.


priority_queue

Default max-heap; priority_queue<T, vector<T>, greater<T>> for min-heap.


Examples

  1. DFS with explicit stack (iterative).
  2. BFS with queue storing {node, distance} for shortest path in unweighted graphs.
  3. Task scheduling with priority_queue and custom operator< or comparator struct.

Common pitfalls

  • No operator[] on stack/queue — drain or use deque/vector if index access is required.
  • pop() returns void — read top()/front() first.
  • Custom types in priority_queue need operator< 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.


  • 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