11

Possible Duplicate:
Can you remove elements from a std::list while iterating through it?

I have a loop in a function, that iterates over an std::list from begin to end.

In each cycle, I perform some checks and maybe do a few manipulations on the current list entry, and in some cases I want to remove it from the list.

Now, as expected my iterator gets invalidated.

  • Is there any way to work around this, to remove elements from a list while iterating over it?
1
  • If it´s possible in your program, you could iterate backwards through the list.
    – Juliano
    Mar 10, 2011 at 20:45

3 Answers 3

16

Catch the return value of erase and use it as your iterator. The return value is an iterator to the next valid location after the erasure.

if(ShouldErase)
{
    iter = list.erase(iter);
}
else
{
    ++iter;
}

Reference

Excerpt:

Return value

A bidirectional iterator pointing to the new location of the element that followed the last element erased by the function call, which is the list end if the operation erased the last element in the sequence.

15

Use postfix increment.

list.erase(it++);

it is increased, so it no longer refers to the erased element, then the previous value of it is given to list.erase. Make sure that you either do list.erase(it++) or ++it in your loop - doing both will skip elements and potentially increment past end of the list.

1
  • 1
    "Lists have the important property (...) that even removal invalidates only the iterators that point to the elements that are removed" (sgi.com/tech/stl/List.html). +1
    – Fred Foo
    Mar 10, 2011 at 20:32
0

Have you considered using the list::remove_if algorithm?

1
  • 2
    He's manipulating the data as well - using remove_if could easily mislead the reader.
    – Erik
    Mar 10, 2011 at 20:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.