gpt4 book ai didi

c++ - for 循环中的 vector 删除函数未正确删除类的 vector

转载 作者:太空宇宙 更新时间:2023-11-04 15:21:28 24 4
gpt4 key购买 nike

我有一个简单的 for 循环:

for (int i = 0; i < c.numparticles; i++)
{
if ( labs((noncollision[i].getypos())) > 5000 )
{
noncollision.erase (noncollision.begin()+i);
}
}

其中 noncollisionparticle 类的 vector 。在此特定示例中,应删除任何 ypos 大于 5000 的 noncollision。我一直在使用大小为 6 的 noncollision,其中 2 个的 ypos 远大于 5000。但是,这个 for 循环只删除其中一个,完全忽略了其他。我怀疑是因为 noncollision 是类的 vector ,所以这个类以某种方式受到保护,或者导致数组函数的行为不同?这是我对 noncollisionparticle 的声明:

vector<particle> noncollision;

class particle{
private:
int xpos;
int ypos;
int xvel;
int yvel;
bool jc; // Has the particle just collided?
public:
etc....
};

谁能解释为什么会这样,以及如何纠正它?我是否需要以某种方式为 particle 类设置“删除功能”?

最佳答案

如果您有两个相邻的候选元素(例如,在 i=5i=6 处),那么您跳过 第二个,因为您刚刚删除了在 i=5 处的那个。 ...然后第二个变成 i=5但是你增加了i得到i=6在下一个循环中。

您需要修复您的循环以正确支持您同时从您正在迭代的同一容器中删除元素这一事实。

通常您会使用实际的迭代器(而不是计数器 i )和 vector::erase方便地返回一个新的迭代器供您在下一次迭代中使用:

vector<particle>::iterator it = noncollision.begin(), end = noncollision.end();
for ( ; it != end; ) { // NB. no `++it` here!
if (labs(it->getypos()) > 5000) {
// erase this element, and get an iterator to the new next one
it = noncollision.erase(it);

// the end's moved, too!
end = noncollision.end();
}
else {
// otherwise, and only otherwise, continue iterating as normal
it++;
}
}

但是,引用 Joe Z 的话:

Also, since erase can be O(N) in the size of a vector, you might (a) benchmark the loop using reverse iterators too, (b) consider copying the not-erased elements into a fresh vector as opposed to deleting elements out of the middle, or (c) using a list<> instead of a vector<> if deleting from the middle is a common operation.


或者,如果您很懒惰,您也可以只颠倒迭代顺序,这样可以保持计数器的完整性 i在这种特定情况下:

for (int i = c.numparticles-1; i >= 0; i--) {
if (labs(noncollision[i].getypos()) > 5000) {
noncollision.erase(noncollision.begin()+i);
}
}

请注意不要更改 i到一个无符号变量(你的编译器可能会警告你这样做 - 即使用 size_t 代替 - 如果 c.numparticles 有一个合理的类型)因为如果你这样做,你的循环将永远不会结束!

关于c++ - for 循环中的 vector 删除函数未正确删除类的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18083130/

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