Haatschii
Haatschii

Reputation: 9309

Is it possible to erase elements of a std::list in a c++11 for each loop

I want to use the new C++11 for each loop to iterate over all elements of a list and erase certains elements. For example

std::list<int> myList;
myList.push_back(1); 
myList.push_back(13);
myList.push_back(9);
myList.push_back(4);

for(int element : myList) {
    if(element > 5) {
        //Do something with the element

        //erase the element
    }else{
        //Do something else with the element
    }
}

Is it possible to do this using the for each loop or do I have to go back to iterators to achive this?

Upvotes: 8

Views: 4209

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279225

You can't erase elements of standard containers in a range-based for loop over that container -- the loop itself has an iterator to the element that you're currently visiting, and erasing it would invalidate that iterator before the loop increments it.

Range-based for is defined in 6.5.4 of the standard to be equivalent to (slightly simplified):

for (auto __begin=begin-expr, __end=end-expr; __begin != __end; ++__begin) {
    for-range-declaration = *__begin;
    statement
}

begin-expr and end-expr have their own lengthy definition, but in your example they are myList.begin() and myList.end() respectively.

Upvotes: 5

Karthik T
Karthik T

Reputation: 31952

You should be able to just do this

myList.erase(std::remove_if(myList.begin(), myList.end(),
    [](int& element) 
    { 
        return element > 5;
    } 
    ),myList.end());

or simply (courtesy Benjamin Lindley)

myList.remove_if(
    [](int& element) 
    { 
        return element > 5;
    } 
    );

Upvotes: 6

Michael Rawson
Michael Rawson

Reputation: 1975

Nope, I don't think so. See this SO answer:

No, you can't. Range-based for is for when you need to access each element of a container once.

You should use the normal for loop or one of it's cousins if you need to modify the container as you go along, access an element more than once, or otherwise iterate in a non-linear fashion through the container.

Upvotes: 0

Related Questions