In C++, std::deque::at() gives you the element stored at one index of a std::deque. 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 <deque> to use it.
This is a member of std::deque<T>, a double-ended queue. A deque is fast at adding and removing at both ends, and it allows access by index like std::vector. Unlike a vector, its elements are stored in several blocks, not in one contiguous block.
Syntax
Call at on the deque you already have. Pass one index inside the brackets.
C++
d.at(2);
d.at(2) = 50;
Call
What it does
d.at(2)
Reads the element at index 2. The index is checked first.
d.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::deque<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 deque.
Frequently Asked Questions
It returns the element stored at a given index of a std::deque. 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. d.at(i) and d[i] take constant time, like a vector. A deque keeps its elements in several blocks, so it is a little slower than a vector, but still fast.
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 deque can also grow at the front, which a vector cannot do quickly.