简体   繁体   English

当没有迭代器失效时,这是否包括结束迭代器?

[英]When no iterators are invalidated, does this include the end iterator?

A std::map s iterators stay valid when inserting elements, eg: std::map s迭代器在插入元素时保持有效,例如:

std::map<std::string,int> my_map;
my_map["foo"] = 1;
my_map["bar"] = 2;

auto it_foo = my_map.find("foo");
auto it_bar = my_map.find("bar"); 

my_map["foobar"] = 3;

after inserting another element (in the last line) the two iterators are still valid. 插入另一个元素(在最后一行)后,两个迭代器仍然有效。 How about the end ? end怎么样? For example: 例如:

auto it_end = my_map.find("something that isnt in the map");

my_map["barfoo"] = 4; // does not invalidate iterators

assert(it_end == my_map.end()); // ??

In other words: If a method does not invalidate iterators (other than those explicitly mentioned, as for example in case of map::erase ) does this mean that also the end is guaranteed to be the same before as after calling the method? 换句话说:如果一个方法没有使迭代器无效(除了那些明确提到的那些,例如在map::erase情况下)这是否意味着在调用方法之前保证end也是相同的?

PS: I am aware that I could just try and see, but this wont tell me whether I can rely on this behaviour. PS:我知道我可以尝试看看,但这不会告诉我是否可以依赖这种行为。

PPS: For example pushing into a std::vector invalidates all iterators, or only the end (when no reallocation took place), but in this case the docs explicitly mention the end . PPS:例如,推入std::vector会使所有迭代器无效,或者只是end (当没有重新分配时),但在这种情况下, 文档明确提到end Following this reasoning, "no iterators are invalidated" should include end , but I am not 100% convinced ;) 根据这个推理,“没有迭代器无效”应该包括end ,但我不是100%确信;)

N4140 23.2.4 Associative containers [associative.reqmts][ 1 ] N4140 23.2.4关联容器[associative.reqmts] [ 1 ]

9 The insert and emplace members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements. 9插入和插入成员不应影响迭代器的有效性和对容器的引用,擦除成员应仅使迭代器和对已擦除元素的引用无效。

Definitely the term iterators refers to all iterators including end . 绝对地,术语迭代器指的是包括end在内的所有迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM