std::deque<T> · C++

operator[] / at

Random access by index in constant time.

reference operator[](size_type pos); reference at(size_type pos);

Complexity

Best caseO(1)
Worst caseO(1)
Extra spaceO(1)

Block index = (offset + pos) / block size, then an index inside the block: two indirections instead of vector's one.

Tested example

std::deque<int> d{10, 20, 30};
d.push_front(5);
assert(d[0] == 5 && d[3] == 30);  // constant-time random access, unlike a linked list
int& middle = d[2];
d.push_back(40);                   // invalidates iterators, but references stay valid
assert(middle == 20);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/deque_examples.cpp

Parameters

pos
0 ≤ pos < size().

Behaviour

Returns
A reference to the element.
Errors and preconditions
operator[] out of range: undefined behaviour. at(): std::out_of_range.
Changes
Nothing.
Memory and invalidation
No allocation.