C++在删除时循环遍历 map

标签 c++

<分区>

要在 C++ 中循环遍历 map ,我们会这样做

map<string,int> mymap;
map<string,int>::iterator it= mymap.begin();
while(it!=mymap.end()) {
   //code here
   it++;
}

如果在“此处的代码”部分我有一个 if 语句,如果评估为真,它会从 map 中删除一个元素怎么办?我的代码应该如何更改才能使其仍然按顺序循环遍历所有 mymap 元素?

最佳答案

http://en.cppreference.com/w/cpp/container/map/erase :

References and iterators to the erased elements are invalidated. Other references and iterators are not affected.

(因此请确保在删除之前递增并保存“下一个”迭代器

编辑:事实上自 C++11 以来,erase 无论如何都会返回下一个迭代器,因此您可以使用它。)

关于C++在删除时循环遍历 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20126684/

相关文章:

C++ 出现 LNK2019 错误,即使没有循环依赖,也没有包含两次

c++ - 数组中的最大 X 值

c++ - 带有MinGW STL的Clang(错误: no member named 'fgetws' in the global namespace)

c++ - 如何将多维映射从 c++ 转换为 perl 中的哈希

c++ - 在C++中将带小数位的数字从char转换为int

c++ - 以对象为参数调用成员函数

c++ - 通过引用调用模板特化

c++ - 如何使用 boost::signals2 存储和转发槽?

c++ - 使用getline从文件中读取多行?

输入多路复用的 C++ 设计模式?