通过 for 循环从 C++ 映射中删除元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5191644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:37:45  来源:igfitidea点击:

Removing elements from a C++ map through a for-loop

c++mapstlc++11

提问by Petter

My STL is a bit rusty, so forgive me for asking a possibly trivial question. Consider the following piece of code:

我的 STL 有点生疏,所以请原谅我提出一个可能微不足道的问题。考虑以下代码:

map<int,int> m;
...
for (auto itr = m.begin(); itr != m.end(); ++itr) {
    if (itr->second == 0) {
        m.erase(itr);
    }
}

The question is: Is it safe to erase elements while looping over the map?

问题是:在遍历地图时擦除元素是否安全?

采纳答案by XAder

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.

我认为你根本不应该使用删除的迭代器 - 在列表的情况下这会导致严重的问题,地图不应该有所不同。

EDITby Matthieu M: this code is well-formed in C++0x and allowed as an extension by MSVC.

Matthieu M编辑:此代码在 C++0x 中格式良好,并允许作为 MSVC 的扩展。

map<int,int> m;
...
auto itr = m.begin();
while (itr != m.end())
{
    if (itr->second == 0) {
        itr = m.erase(itr);
    }
    else 
    {
        itr++;
    }
}

回答by Erik

Yes, but not the way you do it. You're invalidating itr when you erase, then incrementing the invalid iterator.

是的,但不是你这样做的方式。您在擦除时使 itr 无效,然后增加无效迭代器。

auto itr = m.begin();
while (itr != m.end()) {
  if (itr->first == 0) {
    m.erase(itr++);
  } else {
    ++itr;
  }
}

回答by decltype

For the example given, It would actually be easier to use the eraseoverload that takes a key as an argument. This function erases all elements in the map with the given key (for a map, this is always either zero or one element)

对于给出的示例,使用将键作为参数的擦除重载实际上会更容易。此函数使用给定的键擦除地图中的所有元素(对于地图,这始终是零或一个元素)

map<int,int> m; 
// ...
m.erase(0); // erase all elements with key equivalent to 0