Is there an equivalent of the at
function for iterators?
For example
std::vector example(10, 0);
const auto it = example.cbegin();
const auto it2 = it + 10;
std::cout << *it2 << std::endl; // does not throw
whereas with at
example.at(10); // throws
Is there an equivalent of the at
function for iterators?
For example
std::vector example(10, 0);
const auto it = example.cbegin();
const auto it2 = it + 10;
std::cout << *it2 << std::endl; // does not throw
whereas with at
example.at(10); // throws
Share
Improve this question
asked Feb 2 at 21:38
user2138149user2138149
17.8k30 gold badges150 silver badges297 bronze badges
3
|
1 Answer
Reset to default 1Iterators do not have at()
member function because it would violate "you only pay for what you use" C++ design principle. In a fully optimized build, a vector iterator is equivalent to a pointer. To support at()
, the iterator must carry valid range information - even when at()
is not used. There are implementation-specific debug builds with "checked iterators" that carry this extra info and fail an assert in case of invalid iterator use.
it + 11
, for example, any access to the iterator is undefined behavior. Including comparing it with another iterator. You really have to do something likeif ( example.end() - it < example.size() ) ...
. – James Kanze Commented Feb 2 at 22:08