std::deque is a container designed for very fast insertion and removal at both ends of the container.
The name is short for double ended queue. Just like vector or list, they support random access operations using operators like []. They don’t store data contiguously in memory and are organised in such a way that insertions and removals at either end:
- happen very fast.
- do not invalidate pointers or references to other elements.
- do not copy any data around.
To use std::deque, we simply include the library and declare our deque:
#include <deque>
...
std::deque<int> data {1,2,3,4,5};
Some common methods of the deque type are push_back, which adds a value to end of the vector, pop_back, which removes a value from the end of a vector as well as push_front and pop_front, at, which gets or sets the value at the specified index, size, which returns how many items are in the array, empty, which checks id the deque is empty, front, which returns the first value, and back which returns the last value. There is also the [] operator for setting and getting values. The difference with at is that at does range checking and throws an exception if we are outside the bounds, so it’s slightly slower but safer.
We can use all the iterators on the deque.