In C++, std::vector::at() gives you the element stored at one index of a std::vector. Counting starts at 0, so the first element is index 0 and the last one is index size() - 1.
The special thing about at() is that it checks the index. If the index is too big, it throws std::out_of_range instead of reading random memory. Include <vector> to use it.
This is a member of std::vector<T>, a dynamic contiguous array. Elements sit in one block, so v[i] and data() are fast. Growing past capacity() reallocates and can invalidate iterators, references, and pointers. Prefer push_back / pop_back at the end; middle inserts shift elements.
Syntax
Call at on the vector you already have. Pass one index inside the brackets.
C++
v.at(2);
v.at(2) = 50;
Call
What it does
v.at(2)
Reads the element at index 2. The index is checked first.
v.at(2) = 50
Changes the element at index 2. This works because at() returns a reference.
Square brackets also work: d[2]. The difference is that [] does not check the index.
std::vector<int> scores(4, 0) creates four elements, all 0.
scores.at(1) = 95 writes straight into index 1 because at() gives back a reference.
The loop uses size() as its limit, so every at(i) call stays inside the vector.
Frequently Asked Questions
It returns the element stored at a given index of a std::vector. It checks the index first and throws std::out_of_range if the index is too large.
Both read an element by index. at() checks the index and throws std::out_of_range for a bad one. operator[] does no check, so a bad index is undefined behavior. operator[] can be slightly faster.
Yes. v.at(i) and v[i] take constant time because a vector stores elements in one contiguous block. That is one reason vector is the default sequence container.
The index type is size_type, which is unsigned. A negative number turns into a very large value, so at() throws std::out_of_range.
Yes. std::vector::at() works in the same way. The difference is that a vector can also grow at the front, which a vector cannot do quickly.