std::queue
std::queue<T> is a first-in, first-out adapter. You push at the back, front and pop at the front. It is not a container with iterators; it is a restricted view over an underlying container, by default std::deque<T>.
Detailed Explanation
A work list, a breadth-first search frontier, a sequence of incoming sockets: those are queues. The rule is FIFO. std::queue exists to make that rule the API. There is no operator[], no begin, no way to sneak an element into the middle without writing a new adapter.
The type is a container adapter. The second template parameter is the underlying container: std::queue<T, std::deque<T>> by default, or std::queue<T, std::list<T>>. The underlying type must provide push_back, pop_front, front, back, empty, and size. A vector does not provide pop_front in O(1), so it is not a legal base.
push / emplace add to the back. front() is the next element to serve. pop() removes it and returns void — you must read front() first. That split is so pop can be given the default exception specification; a pop that returned T by value could throw on the copy after the element was already removed.
back() exists for inspection of the most recently pushed element. empty and size forward to the underlying container.
There are no iterators. To dump a queue for logging you have to pop a copy, or you pick a container that is not wrapped. That is the point of the adapter: the compiler stops you from breaking FIFO.
BFS uses a queue. The pattern is: push the start, then while not empty, pop, visit neighbours, push unseen neighbours. See the algorithms page for the full walk.
std::queue is not thread-safe. A producer-consumer queue needs a mutex (or a lock-free library type). Putting a queue in a global and pushing from two threads is a data race.
std::priority_queue is not a FIFO queue; it is a heap. std::deque used directly is a queue plus random access. Use the adapter when you want the restriction.
Code Examples
#include <iostream>
#include <queue>
#include <string>
int main() {
std::queue<std::string> jobs;
jobs.push("fetch");
jobs.push("parse");
while (!jobs.empty()) {
std::cout << jobs.front() << '\n';
jobs.pop();
}
// prints:
// fetch
// parse
}#include <list>
#include <queue>
int main() {
std::queue<int, std::list<int>> q;
q.push(1);
q.push(2);
q.pop();
// q.front() == 2
}Common Gotchas
`pop()` returns `void`
`auto x = q.pop();` does not compile. Write `auto x = q.front(); q.pop();`.
`front()` on an empty queue is undefined behaviour
check `empty()` first.
No iterators
you cannot range-for a `queue`. If you need to walk without consuming, use a `deque` directly.
Not synchronized
two threads calling `push` without a lock is a data race, even if each operation looks atomic in the source.