Removing item from vector while iterating?(迭代时从向量中删除项目?)
问题描述
我有一个向量,其中包含活动或非活动的项目.我希望此向量的大小保持较小以解决性能问题,因此我希望从向量中删除已标记为非活动的项目.我在迭代时尝试这样做,但我收到错误向量迭代器不兼容".
I have a vector that holds items that are either active or inactive. I want the size of this vector to stay small for performance issues, so I want items that have been marked inactive to be erased from the vector. I tried doing this while iterating but I am getting the error "vector iterators incompatible".
vector<Orb>::iterator i = orbsList.begin();
while(i != orbsList.end()) {
bool isActive = (*i).active;
if(!isActive) {
orbsList.erase(i++);
}
else {
// do something with *i
++i;
}
}
推荐答案
过去我做过的最易读的方法是使用 std::vector::erase
结合 std::remove_if
.在下面的示例中,我使用此组合从向量中删除任何小于 10 的数字.
The most readable way I've done this in the past is to use std::vector::erase
combined with std::remove_if
. In the example below, I use this combination to remove any number less than 10 from a vector.
(对于非 c++0x,您可以将下面的 lambda 替换为您自己的谓词:)
// a list of ints
int myInts[] = {1, 7, 8, 4, 5, 10, 15, 22, 50. 29};
std::vector v(myInts, myInts + sizeof(myInts) / sizeof(int));
// get rid of anything < 10
v.erase(std::remove_if(v.begin(), v.end(),
[](int i) { return i < 10; }), v.end());
这篇关于迭代时从向量中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:迭代时从向量中删除项目?


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01