问题描述
我有这样的代码:
for (std::list<item*>::iterator i=items.begin();i!=items.end();i++)
{
bool isActive = (*i)->update();
//if (!isActive)
// items.remove(*i);
//else
other_code_involving(*i);
}
items.remove_if(CheckItemNotActive);
我想在更新后立即删除非活动项目,以避免再次走过列表。但是如果我添加注释行,当我得到一个错误,当我得到 i ++
:列表迭代器不可增量。我尝试了一些替代品,在for语句中没有增加,但我无法得到任何工作。
I'd like remove inactive items immediately after update them, inorder to avoid walking the list again. But if I add the commented-out lines, I get an error when I get to i++
: "List iterator not incrementable". I tried some alternates which didn't increment in the for statement, but I couldn't get anything to work.
在你走路时,最好的方法是删除项目一个std :: list?
What's the best way to remove items as you are walking a std::list?
推荐答案
你必须首先递增迭代器(使用i ++),然后删除上一个元素,通过使用从i ++返回的值)。您可以将代码更改为while循环,如下所示:
You have to increment the iterator first (with i++) and then remove the previous element (e.g., by using the returned value from i++). You can change the code to a while loop like so:
std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
bool isActive = (*i)->update();
if (!isActive)
{
items.erase(i++); // alternatively, i = items.erase(i);
}
else
{
other_code_involving(*i);
++i;
}
}
这篇关于你可以从std :: list中删除元素,而迭代通过它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!