Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ std::list: Erasing / removing elements while iterating [duplicate]

Tags:

c++

list

stl

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?
like image 607
Jarx Avatar asked Mar 10 '11 20:03

Jarx


1 Answers

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.

like image 65
Sion Sheevok Avatar answered Oct 27 '22 10:10

Sion Sheevok