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

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

    Example with std::vector

    #include 
    
    using namespace std;
    
    int main()
    {
    
       typedef vector  int_vector;
    
       int_vector v(10);
    
       // Fill as: 0,1,2,0,1,2 etc
       for (size_t i = 0; i < v.size(); ++i){
          v[i] = i % 3;
       }
    
       // Remove every element where value == 1    
       for (int_vector::iterator it = v.begin(); it != v.end(); /* BLANK */){
          if (*it == 1){
             it = v.erase(it);
          } else {
             ++it;
          }
       }
    
    }
    

提交回复
热议问题