<分区>
要在 C++ 中循环遍历 map ,我们会这样做
map<string,int> mymap;
map<string,int>::iterator it= mymap.begin();
while(it!=mymap.end()) {
//code here
it++;
}
如果在“此处的代码”部分我有一个 if 语句,如果评估为真,它会从 map 中删除一个元素怎么办?我的代码应该如何更改才能使其仍然按顺序循环遍历所有 mymap 元素?
标签 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/