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

前端 未结 9 1372
无人及你
无人及你 2020-12-01 07:55

Allegedly you cannot just erase/remove an element in a container while iterating as iterator becomes invalid. What are the (safe) ways to remove the elements that meet a cer

9条回答
  •  孤城傲影
    2020-12-01 08:29

    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;
        }
    }
    

提交回复
热议问题