是否可以为每个循环删除c ++ 11中std :: list的元素 [英] Is it possible to erase elements of a std::list in a c++11 for each loop
本文介绍了是否可以为每个循环删除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;
}
);
这篇关于是否可以为每个循环删除c ++ 11中std :: list的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文