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

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

    bool IsOdd( int i )
    {
        return (i&1)!=0;
    }
    
    int a[] = {1,2,3,4,5};
    vector v( a, a + 5 );
    v.erase( remove_if( v.begin(), v.end(), bind1st( equal_to(), 4 ) ), v.end() );
    // v contains {1,2,3,5}
    v.erase( remove_if( v.begin(), v.end(), IsOdd ), v.end() );
    // v contains {2}
    

提交回复
热议问题