gpt4 book ai didi

c++ - 您可以在迭代时从 std::list 中删除元素吗?

转载 作者:IT老高 更新时间:2023-10-28 11:26:05 26 4
gpt4 key购买 nike

我的代码如下所示:

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++ 时会出现错误:“List iterator not incrementable”。我尝试了一些在 for 语句中没有增加的替代方法,但我什么也做不了。

当您在 std::list 中行走时删除项目的最佳方法是什么?

最佳答案

您必须首先增加迭代器(使用 i++),然后删除前一个元素(例如,使用 i++ 的返回值)。您可以将代码更改为 while 循环,如下所示:

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

关于c++ - 您可以在迭代时从 std::list 中删除元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/596162/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com