In C++, std::deque<T> is a container that holds a row of elements of type T. The word deque (say “deck”) means double-ended queue: you can add and remove elements at both the front and the back, and both are fast.
A deque also allows access by index, so d[2] and d.at(2) work just like in a std::vector. The difference is how the data is stored. A deque keeps its elements in several blocks, so it is not contiguous. Common functions are push_front(), push_back(), front(), and back(). Include <deque> to use it.
This page teaches what a std::deque is. The Deque Functions index lists every function guide in this series.
Why choose a deque?
Choose a deque when you need to add or remove at both ends, for example for a queue, a sliding window, or a history list. If you only add at the back, a std::vector is usually the simpler choice.
Syntax
C++ Syntax
Common ways to create and use a std::deque:
C++
#include <deque>
#include <iostream>
std::deque<int> a; // empty deque
std::deque<int> b = {1, 2, 3}; // three elements
std::deque<int> c(5, 0); // five zeros
b.push_front(0); // 0 1 2 3
b.push_back(4); // 0 1 2 3 4
int first = b.front(); // 0
int last = b.back(); // 4
int x = b[2]; // 2, no check
b.pop_front(); // 1 2 3 4
b.pop_back(); // 1 2 3
Reference
std::deque vs std::vector vs std::list
The three containers look alike but behave differently. Here is a quick comparison:
Feature
std::vector
std::deque
std::list
Add / remove at the back
Fast
Fast
Fast
Add / remove at the front
Slow (no push_front())
Fast
Fast
Access by index d[i]
Fast
Fast
Not available
Insert in the middle
Slow
Slow
Fast (with an iterator)
Memory layout
One block
Several blocks
Separate nodes
capacity() and reserve()
Yes
No
No
Code
C++ Examples
Three short programs that show how std::deque works.
Example 1 — Add at Both Ends with push_front() and push_back()
A first program that adds to the front and the back, then reads both ends.
std::deque<T> is a container from <deque>. The name means double-ended queue. It can add and remove elements quickly at both the front and the back, and it allows access by index like a vector.
Both allow access by index. A vector stores everything in one block and is fast only at the back. A deque stores elements in several blocks and is fast at both the front and the back. A vector has no push_front().
A list is made of separate nodes, so it has no access by index, but it can insert in the middle quickly once you have an iterator. A deque allows d[i] and is faster to loop through in most programs.
No. A deque keeps its elements in several blocks. So you must not treat &d[0] as a plain array of all elements. Use a std::vector if you need one contiguous block.
Open the C++ std::deque Functions index. It lists every member function, from at() and push_front() to swap(), each with its own tutorial.