C ++ std :: list: erasing / deleting elements during iteration

Possible duplicate:
Can you remove items from std :: list during iteration through it?

I have a loop in a function that iterates over std::list from start to finish.

In each cycle, I do some checks and maybe do some manipulations with the current list, and in some cases I want to remove it from the list .

Now, as expected, my iterator is getting invalid.

  • Is there any way around this to remove items from the list, iterating over it?
+8
c ++ list stl
source share
3 answers

Use postfix increment.

 list.erase(it++); 

it increases, so it no longer refers to the element to be erased, then the previous value of it assigned to list.erase . Make sure that you either do list.erase(it++) or ++it in your loop - doing both will skip items and potentially increase the previous end of the list.

+14
source share

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

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

Reference

Excerpts:

Return value

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

+14
source share

Do you consider using the list::remove_if ?

0
source share

All Articles