我有这样的 map 定义和后续操作。
map<int,string> m;
m.insert(std::pair<int,string>(1,"A");
m.insert(std::pair<int,string>(2,"B");
m.insert(std::pair<int,string>(3,"C");
m.insert(std::pair<int,string>(4,"D");
auto it = m.find(2);
m.erase(m.find(3));
cout<< it->second;
删除其他元素后“它”是否有效?
最佳答案
Will "it" be valid after an erase to some other element ?
是的,std::map::erase
只会使对已删除元素的引用和迭代器无效。
References and iterators to the erased elements are invalidated. Other references and iterators are not affected.
注意代码 m.erase(m.find(3));
有一个潜在的问题,因为 std::map::find
如果未找到任何内容,将返回 end()
迭代器,但 end()
迭代器不能与 std::map::erase
一起使用。
The iterator
pos
must be valid and dereferenceable. Thus theend()
iterator (which is valid, but is not dereferencable) cannot be used as a value forpos
.
关于c++ - 有序映射的迭代器有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37562385/