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 caseO(1)
Worst caseO(1)
Extra spaceO(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);
Runs in the test suite on C++23, GCC 15.3 (libstdc++) · examples/cpp/collections/vector_examples.cpp

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.