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

蹲街弑〆低调 提交于 2019-12-23 07:32:41

问题


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?


回答1:


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;
    } 
    );



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/14304950/is-it-possible-to-erase-elements-of-a-stdlist-in-a-c11-for-each-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!