std::deque<T> · C++

push_back / push_front

Adds an element at either end.

void push_back(const T& value); void push_front(const T& value); // and emplace_*

Complexity

Best caseO(1)
Worst caseO(1) (the standard says inserting at either end always takes constant time)
Extra spaceO(1) amortized (a new block now and then)

Construct into the first or last block; allocate a new block when that one is full. Existing elements never move.

Tested example

std::deque<int> d{2, 3};
d.push_front(1);  // constant time at either end
d.push_back(4);
assert((d == std::deque<int>{1, 2, 3, 4}));
std::queue<std::string> q;  // std::queue adapts a deque by default
q.push("first");
q.push("second");
assert(q.front() == "first");
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/deque_examples.cpp

Parameters

value
The element.

Behaviour

Returns
Nothing (emplace_* return a reference since C++17).
Errors and preconditions
std::bad_alloc; if an exception is thrown, there is no effect.
Changes
size() increases by 1.
Memory and invalidation
Invalidates all iterators; references and pointers to existing elements remain valid.