问题描述
我可以在std :: list上删除元素吗?例如:
Can I remove elements from std::list, when I'm iterating on it? For example so:
std::list<int> lst;
//....
for (std::list<int> itr = lst.begin(); itr != lst.end(); itr++)
{
if (*itr > 10)
lst.remove(*itr);
}
?
为什么?
?And why?
推荐答案
正确的代码如下:
for (std::list<int>::iterator itr = lst.begin(); itr != lst.end(); /*nothing*/)
{
if (*itr > 10)
itr = lst.erase(itr);
else
++itr;
}
从列表中删除项目时,可以使迭代器无效(如果因此,您需要使用 erase
进行删除(返回指向下一个项目的有效迭代器)。
When you delete an item from the list, you may invalidate the iterator (if it points to the item being deleted.) Therefore you need to delete using erase
(which returns a valid iterator pointing to the next item).
更好的主意是使用:
Even better idea would be using std::remove_if
:
bool greater_than_10(int x)
{
return x > 10;
}
lst.remove_if(greater_than_10);
如果您的编译器支持,您可以更短一些:
If your compiler supports lambdas, you can put it even shorter:
lst.remove_if([](int x){ return x > 10; });
(我没有测试这段代码,因为我的编译器不是那么新; lambda函数是
(I didn't test this code, as my compiler is not so new; the lambda function is thankfully stolen from @John Dibling's answer.)
实际上,从列表中删除会使。但是请提防其他STL容器不具有此属性。
Actually, erasing from list invalidates only the iterators pointing to the item being deleted. Beware however that other STL containers don't have this property.
因此,简而言之:一般而言,您不应遍历列表时删除列表中的项目,因为删除操作可能会使迭代器无效(并且程序可能会崩溃)。但是,如果您完全确定要删除的项不是删除时使用的任何迭代器引用的值,则可以删除。
So, in short: generally speaking, you should not delete the items from the list while iterating through it, because the deletion may invalidate the iterator (and the program will possibly crash). If you are however completely sure that the items which you delete are not the values referenced by any of the iterators which you use at the moment of deletion, you may delete.
请注意,对于其他STL容器(例如向量),约束甚至更加严格:从容器中删除不仅会使指向已删除项目的迭代器无效,而且使其他迭代器也无效!因此,在遍历它们的同时从那些容器中删除会带来更多问题。
Beware that for the other STL containers (e.g. vectors) the constraint is even more strict: deleting from the container invalidates not only iterators pointing to the deleted item, but possibly other iterators, too! So deleting from that containers while iterating through them is even more problematic.
这篇关于迭代时是否可以从std :: list中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!