std::deque
std::deque<T> is a double-ended queue: O(1) push_front, push_back, pop_front, and pop_back, plus random-access operator[]. Elements live in fixed-size chunks, not one contiguous buffer.
Detailed Explanation
A vector is fast at the back and slow at the front. A list is fast at both ends and slow at indexing. A deque sits in the middle: grow either end without moving existing elements (most of the time), and still index in O(1).
The usual layout is an array of pointers to chunks (blocks of T). push_back fills the last chunk and allocates a new one when it is full. push_front fills the first chunk backwards and allocates a new chunk when needed. Indexing computes a chunk and an offset. That is why data() does not exist: there is no single pointer to all elements.
When to use it:
- A queue you will also peek by index.
- A sliding window that pushes back and pops front (though a vector plus a head index, or
std::queue, may be simpler). - Growing a sequence at both ends without
list's per-element allocation.
When not to:
- You need a contiguous buffer for a C API (
vector,array). - You only push back (
vectoris simpler and faster). - You iterate the whole container in a tight numeric loop (
vectorwins on cache).
Iterator invalidation is stricter than people expect. push_front and push_back invalidate all iterators (they may reallocate the map of chunks) but do not invalidate pointers and references to elements. insert and erase in the middle invalidate everything. pop_front and pop_back invalidate only iterators to the removed element. Check your library's notes; the standard's rules are the ones to write to.
std::queue and std::stack default to a deque as their underlying container. If you only use those adapters, you may never name deque yourself.
shrink_to_fit exists and is a hint. There is no capacity() in the vector sense that you can rely on portably.
C++ deque is not the same as a ring buffer you write yourself. A ring buffer over a vector can be faster for a fixed window. Use deque when the window must grow without a fixed cap.
Code Examples
#include <deque>
#include <iostream>
int main() {
std::deque<int> q;
q.push_back(2);
q.push_back(3);
q.push_front(1);
std::cout << q[0] << q[1] << q[2] << '\n'; // prints: 123
q.pop_front();
std::cout << q.front() << '\n'; // prints: 2
}#include <deque>
#include <string>
int main() {
std::deque<std::string> lines;
lines.emplace_back("tail");
lines.emplace_front("head");
// lines is {"head", "tail"}
}Common Gotchas
Assuming `&d[0]` is a C array
chunks are separate allocations. Passing `&d[0]` and `d.size()` to a function that walks contiguous memory is undefined once you leave the first chunk.
`push_back` invalidates iterators
holding `d.begin()` across a push is a bug even if references to elements remain valid.
Prefer `vector` when you only grow at the back
deque's chunk map is extra machinery you do not need.
Middle `insert` is O(n) and invalidates everything
a deque is not a list.