c++ - 有序映射的迭代器有效性

标签 c++ iterator stdmap

我有这样的 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 the end() iterator (which is valid, but is not dereferencable) cannot be used as a value for pos.

关于c++ - 有序映射的迭代器有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37562385/

相关文章:

c++ - 子弹算法在 X 轴上旋转有问题

Android LRUCache 检索

c++ - 接口(interface)传递接口(interface)容器

c++ - 将多个带有 vector 的 map 合并为一张 map

c++ - 删除树中的所有节点 - C++

C++ libCurl : Post callback function to send more than one byte

c++ - 编辑控件不会获得焦点! Win32 C++

python - 测试某个值是否不是由迭代器产生的

c++ - std::map 中的 std::string 导致 Valgrind 内存泄漏

c++ - 将 std::initializer_list 插入 std::map