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

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

    I prefer version with while:

    typedef std::list list_t;
    void f( void ) {
      // Remove items from list
      list_t::iterator it = sample_list.begin();
      while ( it != sample_list.end() ) {
        if ( it->condition == true ) {
          it = sample_list.erase( it );
        } else ++it;    
      }
    }
    

    With while there is no danger to increment it twice as it could be in for loop.

提交回复
热议问题