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 case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(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);
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.