Can you remove elements from a std::list while iterating through it?(您可以在迭代时从 std::list 中删除元素吗?)
问题描述
我有这样的代码:
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 语句中没有增加的替代方法,但我无法得到任何工作.
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 中删除元素吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:您可以在迭代时从 std::list 中删除元素吗?


基础教程推荐
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01