C++ 如果在从头到尾迭代时在 map 元素上调用 erase() 会发生什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/263945/
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-27 14:08:31  来源:igfitidea点击:

What happens if you call erase() on a map element while iterating from begin to end?

c++stliterator

提问by Matthew Smith

In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?

在下面的代码中,我遍历地图并测试是否需要擦除元素。擦除元素并继续迭代是否安全,或者我是否需要在另一个容器中收集密钥并执行第二个循环来调用擦除()?

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
    if (pm_it->second == delete_this_id) {
        port_map.erase(pm_it->first);
    }
}

UPDATE: Of course, I then read this questionwhich I didn't think would be related but answers my question.

更新:当然,然后我阅读了这个我认为不会相关但回答我的问题的问题。

回答by Martin York

C++11

C++11

This has been fixed in C++11 (or erase has been improved/made consistent across all container types).
The erase method now returns the next iterator.

这已在 C++11 中得到修复(或擦除已在所有容器类型中得到改进/保持一致)。
擦除方法现在返回下一个迭代器。

auto pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        pm_it = port_map.erase(pm_it);
    }
    else
    {
        ++pm_it;
    }
}

C++03

C++03

Erasing elements in a map does not invalidate any iterators.
(apart from iterators on the element that was deleted)

擦除地图中的元素不会使任何迭代器失效。
(除了被删除元素上的迭代器)

Actually inserting or deleting does not invalidate any of the iterators:

实际上插入或删除不会使任何迭代器失效:

Also see this answer:
Mark Ransom Technique

另请参阅此答案:
Mark Ransom Technique

But you do need to update your code:
In your code you increment pm_it after calling erase. At this point it is too late and is already invalidated.

但是您确实需要更新您的代码:
在您的代码中,您在调用擦除后增加 pm_it。此时为时已晚,已经失效。

map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();
while(pm_it != port_map.end())
{
    if (pm_it->second == delete_this_id)
    {
        port_map.erase(pm_it++);  // Use iterator.
                                  // Note the post increment.
                                  // Increments the iterator but returns the
                                  // original value for use by erase 
    }
    else
    {
        ++pm_it;           // Can use pre-increment in this case
                           // To make sure you have the efficient version
    }
}

回答by AlaaShaker

Here's how I do that ...

这是我如何做到的......

typedef map<string, string>   StringsMap;
typedef StringsMap::iterator  StrinsMapIterator;

StringsMap m_TheMap; // Your map, fill it up with data    

bool IsTheOneToDelete(string str)
{
     return true; // Add your deletion criteria logic here
}

void SelectiveDelete()
{
     StringsMapIter itBegin = m_TheMap.begin();
     StringsMapIter itEnd   = m_TheMap.end();
     StringsMapIter itTemp;

     while (itBegin != itEnd)
     {
          if (IsTheOneToDelete(itBegin->second)) // Criteria checking here
          {
               itTemp = itBegin;          // Keep a reference to the iter
               ++itBegin;                 // Advance in the map
               m_TheMap.erase(itTemp);    // Erase it !!!
          }
          else
               ++itBegin;                 // Just move on ...
     }
}

回答by ravenspoint

This is how I would do it, approximately:

这就是我将如何做到的,大约:

bool is_remove( pair<string, SerialdMsg::SerialFunction_t> val )
{
    return val.second == delete_this_id;
}

map<string, SerialdMsg::SerialFunction_t>::iterator new_end = 
    remove_if (port_map.begin( ), port_map.end( ), is_remove );

port_map.erase (new_end, port_map.end( ) );

There is something odd about

有一些奇怪的事情

val.second == delete_this_id

but I just copied it from your example code.

但我只是从您的示例代码中复制了它。