Removing items during iteration through a list - security

I was wondering if something like that is safe ...

// Iterating through a <list>
while ( iter != seq.end()) {
  if ( test ) {
    iter = seq.erase( iter );
  } else {
    ++iter;
 }

I know that iterating through a vector this way will invalidate the iterator, but will it happen on the list? I assume that since the list is sequential with pointers and not “next to” each other in memory, but any reassurance would be helpful.

+5
source share
7 answers

This is just fine, because the erase method returns a new valid iterator.

+6
source

Yes, this is the standard way to do this. See “Effective STL”, paragraph 9 (page 46).

+1
source

- std::list::erase(): " ".

, , , - , , std::remove_if().

+1

erase STL. std::list . erase , ( list.end()).

, , :

.. it = l.begin();
while(it != l.end()) {
   it = l.erase(it);
}

- ( ):

for (.. it  = l.begin; it != l.end(); ++it) {
      it = l.erase(it);
   }

l.end(), ( ). Baamm.

+1

, . erase() , , . erase() iter, .

0

As others have explained, your code does not invalidate the iterator used in this function. However, it invalidates other iterators if the collection is a vector, but not if the collection is a list.

0
source

As others have said, yes, it will work. But I recommend using list :: remove_if instead , as this is more expressive.

0
source

All Articles