In C++, std::array::at() gives you the element stored at one index of a std::array. 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 <array> to use it.
This is a member of std::array<T, N>, not of a plain C array and not of std::vector. A std::array has a fixed size N that is part of its type, and it lives on the stack like a normal variable.
Syntax
Call at on the array you already have. Pass one index inside the brackets.
C++
nums.at(2);
nums.at(2) = 50;
Call
What it does
nums.at(2)
Reads the element at index 2. The index is checked first.
nums.at(2) = 50
Changes the element at index 2. This works because at() returns a reference.
Square brackets also work: nums[2]. The difference is that [] does not check the index.
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 array.
Frequently Asked Questions
It returns the element stored at a given index of a std::array. 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. at() returns a reference, so nums.at(1) = 10; changes the element. For a const array it returns a const reference, so you can only read.
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 std::array has a fixed size known at compile time, while a vector can grow.