运行

时间:2017-01-04 17:22:42

标签: c++ visual-studio list visual-studio-2015 iterator

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”中移除球。程序正常运行,直到单击。单击时,它会从标题中显示错误。怎么样?

1 个答案:

答案 0 :(得分:2)

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;
        }
    }
}