std::vector<T> · C++
operator[] / at
Element access by index; only at() checks bounds.
reference operator[](size_type pos); reference at(size_type pos);
Complexity
| Best case | O(1) |
|---|---|
| Worst case | O(1) |
| Extra space | O(1) |
Pointer arithmetic on contiguous storage.
Tested example
std::vector<int> v{1, 2, 3};
v[1] = 20; // no bounds check: v[3] would be undefined behaviour
assert(v[1] == 20);
bool threw = false;
try {
(void)v.at(3); // bounds-checked
} catch (const std::out_of_range&) {
threw = true;
}
assert(threw);
Parameters
- pos
- 0 ≤ pos < size().
Behaviour
- Returns
- A reference to the element.
- Errors and preconditions
- operator[]: pos ≥ size() is undefined behaviour. at(): throws std::out_of_range.
- Changes
- Nothing (unless you write through the reference).
- Memory and invalidation
- No allocation.