2017-01-04 35 views
0
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」中移除球。程序正常運行,直到點擊。當我點擊時,它會從標題中給出一個錯誤。它是如何正確的?運行時「列表迭代器不兼容」

+0

你在遍歷'ballList'(爲什麼?)迭代兩次,並且使迭代器無效。 – molbdnilo

+0

刪除外部循環,然後嘗試'it = ballList.erase(it)'而不是'ballList.remove(ball)' – Chad

+0

對於每個或基於範圍的for循環,都不應該改變容器,而只應改變容器的元素。 – NathanOliver

回答

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