Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removal of elements during iteration through a list - safety

Tags:

c++

iteration

I was wondering if something like this 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 in this way would invalidate the iterator, but would the same thing occur in a list? I assume not since a list is sequential through pointers rather than being "next" to each other in memory, but any reassurance would be helpful.

like image 644
Anonymous Avatar asked Feb 27 '23 17:02

Anonymous


2 Answers

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

like image 93
JaredPar Avatar answered Mar 02 '23 07:03

JaredPar


Yes -- std::list::erase(): "Invalidates only the iterators and references to the erased elements."

That said, you probably shouldn't do this at all -- you seem to be trying to imitate std::remove_if().

like image 25
Jerry Coffin Avatar answered Mar 02 '23 05:03

Jerry Coffin