RMRMaster RMRMaster - 3 years ago 169
C++ Question

c++ Remove iterator in loop (map of maps)

I have a map of maps and during the iteration i need to delete the iterator like i show in the follow code. What is the best way to do this?

for (Map1_t::iterator itOutMap = map1.begin(); itOutMap != map1.end(); ++ itOutMap)
{
for (Map2_t::iterator itInMap = itOutMap->second.begin(); itInMap != itOutMap->second.end(); ++itInMap)
{
if (itInMap->first == USER_REQ_TYPE)
{
// need to delete the current itInMap
}
}
}

Answer Source

You can use std::map::erase() http://en.cppreference.com/w/cpp/container/map/erase the example in that page does exactly what you are asking

for (Map1_t::iterator itOutMap = map1.begin(); itOutMap != map1.end(); ++ itOutMap)
  {
    for (Map2_t::iterator itInMap = itOutMap->second.begin(); itInMap != itOutMap->second.end(); )
    {
      if (itInMap->first ==  USER_REQ_TYPE)
      {
        itInMap=itOutMap->second.erase(itInMap);
      }
      else ++itInMap;
    }

  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download