C++ vector and map delete method of recommended

  • 2020-05-10 18:33:39
  • OfStack

1. Continuous memory sequence container (vector,string,deque)

The return value of the erase method of the sequence container is a valid iterator that points to the element immediately after the element is deleted and can be safely deleted based on this return value.


vector<int> c;

for(vector<int>::iterator it = c.begin(); it != c.end();)

{ if(need_delete())  

    it = c.erase(it); 

  else  

     ++it; 

}

2. The associative container (set multiset, map, multimap)

The erase method of associating containers does not return a value, and the deleted iterator fails, so you must make sure you get the next iterator before you delete it. You can use the "postincrementing iterator" technique.


map<int,int> m;

for(map<int,int>::iterator it = m.begin(); it != m.end();)

{

  if(need_delete())  

      m.erase(it++); 

  else  

      ++it;

}

m.erase gets a copy of it. it has been incremented before erase actually starts.

So erase gets the current iterator, it has already ++ before erase's internal work starts, which is just what we need.


Related articles: