Erase/Remove contents from the map (or any other STL container) while iterating it

You can as long as you don’t invalidate your iterator after you’ve erased it:

MyContainer::iterator it = myContainer.begin();
while(it != myContainer.end())
{
    if (*it == matchingValue)
    {
       myContainer.erase(it++);
    }
    else
    {
        ++it;
    }
}

Leave a Comment