Core Module
12 min forge
C++ STL Queue
Mastering First-In-First-Out (FIFO) data structures.
C++ STL Queue
π What is it
std::queue is a container adaptor that gives the programmer the functionality of a queue - specifically, a FIFO (first-in, first-out) data structure.
β‘ When to use
Essential for Breadth-First Search (BFS), job scheduling, and handling requests in a sequential manner.
π§ Time complexity
- Push: $O(1)$
- Pop: $O(1)$
- Front: $O(1)$
π» Code example
cpp Standard#include <queue> std::queue<int> q; q.push(10); q.push(20); std::cout << q.front(); // 10 q.pop(); std::cout << q.front(); // 20
β Common mistakes
- Empty Queue Pop: Trying to
pop()or accessfront()on an empty queue (always checkq.empty()first). - Thinking it's a priority queue (which sorts elements).
- Trying to access elements at the back or middle (use
std::dequeorstd::vectorfor that).