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

Mat*_*ith 132 c++ iterator stl

在下面的代码中,我遍历一个map并测试是否需要擦除一个元素.擦除元素并继续迭代是否安全,或者我是否需要在另一个容器中收集密钥并执行第二个循环来调用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新:当然,我读了这个问题,我认为这个问题没有关系,但回答了我的问题.

Mar*_*ork 183

C++ 11

这已在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

C++ 03

擦除映射中的元素不会使任何迭代器无效.
(除了被删除的元素上的迭代器)

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

另见这个答案:
Mark Ransom Technique

但是你需要更新你的代码:
在你的代码中,你在调用erase后递增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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @DavidRodríguez - dribeas:是的.该标准保证在调用函数之前将完全评估所有参数表达式.它是传递给erase函数()的后增量的结果.所以是的,pm_it的后增量将在调用erase()之前完成. (4认同)
  • @iboisver:关于向量.使用erase()会使擦除点(不仅仅是结尾)之后的数组的所有迭代器无效,这是`Sequence`容器的属性.`Associative`容器的特殊属性是迭代器不会被erase或insert无效(除非它们指向被擦除的元素).在适当的问题http://stackoverflow.com/a/3938847/14065中详细介绍了向量和擦除usign迭代器 (3认同)

Ala*_*ker 12

这就是我这样做的方式......

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 ...
     }
}
Run Code Online (Sandbox Code Playgroud)