通过for循环从C ++映射中删除元素 [英] Removing elements from a C++ map through a for-loop
本文介绍了通过for循环从C ++映射中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的STL有点生锈,所以请原谅我问一个可能琐碎的问题。考虑下面的代码:
My STL is a bit rusty, so forgive me for asking a possibly trivial question. Consider the following piece of code:
map<int,int> m;
...
for (auto itr = m.begin(); itr != m.end(); ++itr) {
if (itr->second == 0) {
m.erase(itr);
}
}
问题是:循环地图?
推荐答案
我认为你不应该使用删除的迭代器 - 如果列表这会导致严重的问题,对于地图而言是不同的。
I think that you shouldn't use removed iterator at all - in case of lists this causes serious problems, shouldn't be different for maps.
EDIT by Matthieu M:这段代码在C ++ 0x中格式良好, 。
EDIT by Matthieu M: this code is well-formed in C++0x and allowed as an extension by MSVC.
map<int,int> m;
...
auto itr = m.begin();
while (itr != m.end())
{
if (itr->second == 0) {
itr = m.erase(itr);
}
else
{
itr++;
}
}
这篇关于通过for循环从C ++映射中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文