C++ · Double-ended queue · container
std::deque<T>
A double-ended queue with constant-time insertion at both ends and constant-time random access; the default storage of std::queue and std::stack.
#include <deque> template<class T, class Allocator = std::allocator<T>> class deque;
C++23
Operations
| Operation | Time | Worst case | Changes the collection |
|---|---|---|---|
| push_back / push_front | O(1) (the standard says inserting at either end always takes constant time) | O(1) (the standard says inserting at either end always takes constant time) | Yes |
| pop_front / pop_back | O(1) | O(1) | Yes |
| operator[] / at | O(1) | O(1) | No |
"Time" shows the amortized, expected or average bound when one applies; open an operation for the full profile and its assumptions.
How it works
- Representation
- A map (array) of pointers to fixed-size blocks. Elements never move when you add at either end, which is why references stay valid.
- Ordering
- Sequence order.
- Duplicates
- Allowed.
- Mutability
- Mutable; owns its elements.
- Memory and ownership
- Not contiguous (no data()); per-block overhead makes small deques larger than small vectors.
- Equality and comparison
- operator== element-wise.
Pitfalls
- push_front and push_back invalidate all iterators but keep references and pointers to elements valid; this asymmetry surprises people.
- pop_front, pop_back, front and back on an empty deque are undefined behaviour.
- Inserting in the middle is linear (it shifts toward the nearer end).
Alternatives
- std::queue / std::stack adapters for a restricted interface
- std::vector when you only use the back
- std::list for O(1) splicing in the middle
In other languages
- C#: Queue<T>
- Python: collections.deque
- Java: ArrayDeque<E>