gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:51:58 26 4
gpt4 key购买 nike

std::map 的迭代器在插入元素时保持有效,例如:

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;

插入另一个元素(在最后一行)后,两个迭代器仍然有效。 end 怎么样?例如:

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()); // ??

换句话说:如果一个方法不使迭代器无效(除了那些明确提到的,例如在 map::erase 的情况下)这是否也意味着 end 保证调用方法前后一致?

PS:我知道我可以尝试看看,但这不会告诉我是否可以依赖这种行为。

PPS:例如,插入 std::vector 会使所有迭代器无效,或仅使 end 无效(当未发生重新分配时),但在这种情况下为 docs明确提及 end。按照这个推理,“没有迭代器是无效的”应该包括 end,但我不是 100% 相信 ;)

最佳答案

N4140 23.2.4 Associative containers [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.

术语迭代器肯定是指所有迭代器,包括end

关于c++ - 当没有迭代器失效时,这是否包括结束迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47576004/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com