此代码是否适用于所有符合标准的 C++ 编译器(适用于 g++)?为什么(如果可能,请提供 c++11 引用资料)?一般而言,std::unordered_map 和关联容器怎么样?
std::map<std::string, std::string> map;
std::map<std::string, std::string>::iterator i(map.end());
map.insert({"bla", ""});
map.insert({"hah", ""});
assert(map.end() == i);
最佳答案
看来您正在寻找有关插入器失效的标准的引述:
对于 set、multiset、map 和 multimap
The insert 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.
对于 unordered_set、unordered_map、unordered_multiset 和 unordered_multimap
The insert members shall not affect the validity of iterators if (N+n) < z * B, where N is the number of elements in the container prior to the insert operation, n is the number of elements inserted, B is the container’s bucket count, and z is the container’s maximum load factor.
因此,对于 map
,插入不会使 end
迭代器失效,但是,对于 unordered_map
,如果添加到现有元素数量超过 bucket_count * max_load_factor
。
关于c++ - 关联容器中的 end() 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9886490/