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

前端 未结 9 1364
无人及你
无人及你 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:18

    Use the fact that the post-decrement operator returns a copy of the iterator before it decrements. Since the decremented iterator is still valid after erasing the current element, the for loop continues to operate as intended.

    #include 
    std::list myList;
    for(int i = 0; i < 10; ++i )
    {
       myList.push_back(i);
    }
    
    int cnt = 0;
    for(std::list::iterator iter = myList.begin(); iter != myList.end(); ++iter)
    {
       if( cnt == 5 )
       {
          myList.erase(iter--);
       }
       ++cnt;
    }
    

    Edit: Doesn't work if you attempt to erase the first element in the list....

提交回复
热议问题