void GameLogic::isHit(int mousePressX, int mousePressY)
{
for each(BallObject* ball in ballList) {
for (it = ballList.begin(); it != ballList.end();)
{
bool isHit = ball->EvaluateHit(mousePressX, mousePressY);
if (isHit == true)
{
mScore++;
ballList.remove(ball);
}
else
{
++it;
}
}
}
我试图通过单击表面(球应该消失)在玩游戏时从“ ballList”中删除球。程序运行正常,直到单击。当我单击时,标题出现错误。怎么了
最佳答案
void GameLogic::isHit(int mousePressX, int mousePressY)
{
// iterate all the balls in the list...
for (it = ballList.begin(); it != ballList.end();)
{
bool isHit = (*it)->EvaluateHit(mousePressX, mousePressY);
if (isHit == true)
{
mScore++;
// This invalidates iterators, and is linear in complexity
// (it iterates the list too, but you're already doing that)
// ballList.remove(ball);
// erase the ball at this iteration, save off the result
// so you can continue iterating
it = ballList.erase(it);
}
else
{
// if the ball wasn't hit, increment the iterator normally
++it;
}
}
}