我有以下代码,但是在运行它时,我间歇性地收到“调试断言失败”错误,其原因是“ vector 迭代器不可取消”。
我要对该程序进行的操作是创建一堆2D形状(正方形和圆形),然后将它们一个接一个地移动,检查碰撞的过程。当两个形状发生碰撞时,我希望将它们删除,直到(最多)剩下一个形状。大约每3次尝试中就有1次导致成功的结果,程序会发现四个碰撞,然后停止。其他时候,它将发现1-3次碰撞,然后出错。
我还应该提到我对C++比较陌生(是的,这是一个类(class)作业),因此,如果我的代码中还有其他菜鸟错误,请指出这些错误!
我自己的移动和碰撞方法看起来不错,因此这里未包括它们。
Square * s1 = new Square(seedCoord(limit), seedCoord(limit), 2.0);
... //There is 9 new shapes created here (squares and circles)
std::vector<Shape*> shape;
shape.push_back(s1);
... //All 9 shapes added to the vector
int m = shape.size();
bool collision = false;
while(m>1) //Keep running until only one shape hasn't collided
{
for (auto i=shape.begin(); i!=(shape.end());) //Perform move on each shape in sequence
{
collision = false; //Set collision boolean to false
(*i)->move(seedCoord(0.5), direction[(rand() % 4)], limit); //Perform move on shape
for (auto j=shape.begin(); j!=(shape.end()-1);) //Check for collision with each shape in sequence
{
if((*i) != (*j)) //Ignore self when checking for collision
{
if((*i)->collide(*j)) //Check for collision
{
std::cout << "Collision between " << (*i) << " and " << (*j) << "\n";
m=m-2; //Lower shapes count by two (ie remove two collided shapes)
delete *i; //Delete pointer to initial shape
i = shape.erase(i); //Erase shape object
delete *j; //Delete pointer to collided shape
j = shape.erase(j); //Erase shape object
collision = true; //Set collision boolean to true
break; //Break out of internal for-loop (shape has been deleted so no more checks are necessary)
}
else
{
j++; //If no collision, move onto next shape
}
}
else
{
j++; //If i=j, move onto next shape
}
}
if(!collision) //If no collision with any shape, move onto next shape
{
i++; //If no collision with any shape, move onto next shape
}
else
{
break; //If collision has occurred, break out of external for-loop (shape has been deleted so no more checks are necessary)
}
}
}
最佳答案
引用cpprefernce on erase:
我的猜测是,当您第二次调用erase(j)
时,就会发生问题,j
是一个迭代器,它引用i
和shape.end()
之间的位置并被无效。