是否可以为每个循环删除c ++ 11中std :: list的元素
问题描述:
我想为每个循环使用新的C ++ 11来遍历列表的所有元素并擦除某些元素。例如,
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
}
}
是否可以使用for每个循环来执行此操作,或者我必须返回迭代器以达到此目的?
Is it possible to do this using the for each loop or do I have to go back to iterators to achive 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;
}
);