5/11/2017

C++: Please very special attention to map element deletion when iterating it

The normal way doesn't work. You need to use this way:
for (auto it = m.cbegin(); it != m.cend() /* not hoisted */; /* no increment */)
{
  if (must_delete)
  {
    m.erase(it++);    // or "it = m.erase(it)" since C++11
  }
  else
  {
    ++it;
  }
}

No comments: