最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c++ - Is there an equivalent of the `at` function for iterators? - Stack Overflow

programmeradmin0浏览0评论

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
  • 3 There is nothing built in. You are responsible to check the iterator after you modify it. – NathanOliver Commented Feb 2 at 21:41
  • 2 Some tool-chains have checking iterators in debug mode, but that's an additional feature and not required. – Richard Critten Commented Feb 2 at 22:08
  • @NathanOliver actually, you'd have to check the iterator before modification. After it + 11, for example, any access to the iterator is undefined behavior. Including comparing it with another iterator. You really have to do something like if ( example.end() - it < example.size() ) .... – James Kanze Commented Feb 2 at 22:08
Add a comment  | 

1 Answer 1

Reset to default 1

Iterators 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.

发布评论

评论列表(0)

  1. 暂无评论