當我通過調試器一步一步地運行程序時,我不會收到此錯誤。然而,當我真正運行程序時,我每次都會得到它。它打破這個循環:列表迭代器不兼容
auto ships = sprites.begin();
auto misscnt = sprites.begin(); misscnt++; misscnt++; //missiles start at the 3rd item on list every time.
while (misscnt != sprites.end()) //Missile Collision
{
ships = sprites.begin();
ships++;
if (dynamic_cast<Missile*>(*misscnt)->Collides((*ships)->GetLeft(), (*ships)->GetTop(), (*ships)->GetWidth(), (*ships)->GetHeight()) && dynamic_cast<Missile*>(*misscnt)->GetID() == "PlayerMiss")
{
ships--;
(*ships)->AddToScore(10);
sys->playSound(FMOD_CHANNEL_FREE, eHit, false, 0);
while (true)
{
ships = sprites.begin();
ships++;
int x, y;
x = rand() % Console::WindowWidth;
y = rand() & Console::WindowHeight;
if ((*ships)->GoodSpot(x, y, *(*--ships)))
{
ships++;
(*ships)->SetLeft(x);
(*ships)->SetTop(y);
break;
}
}
delete (*misscnt);
sprites.erase(misscnt);
ships = sprites.begin();
}
else if (dynamic_cast<Missile*>((*misscnt))->Collides((*ships)->GetLeft(), (*ships)->GetTop(), (*ships)->GetWidth(), (*ships)->GetHeight()) && dynamic_cast<Missile*>((*misscnt))->GetID() == "EnemyMiss")
{
(*ships)->SetLives((*ships)->GetLives() - 1);
if ((*ships)->GetLives() > 1)
sys->playSound(FMOD_CHANNEL_FREE, pHit, false, 0);
if ((*ships)->GetLives() == 1)
sys->playSound(FMOD_CHANNEL_FREE, LastLife, false, 0);
if ((*ships)->GetLives() == 0)
{
bgmusic->setPaused(true);
sys->playSound(FMOD_CHANNEL_FREE, pDie, false, 0);
Sleep(4000);
play = false;
break;
}
while (true)
{
int x, y;
x = rand() % Console::WindowWidth;
y = rand() & Console::WindowHeight;
if ((*ships)->GoodSpot(x, y, *(*++ships)))
{
ships--;
(*ships)->SetLeft(x);
(*ships)->SetTop(y);
break;
}
}
delete (*misscnt);
sprites.erase(misscnt);
ships = sprites.begin();
}
else
misscnt++;
}
該計劃從未進入任如果還是否則,如果機構因此每當導彈被觸發它被添加到列表中。在循環中,如果導彈在任何情況下不會碰撞,它應該增加misscnt並檢查下一個導彈(如果有的話)。
編輯:錯誤說
列表迭代不相容 文件:: F:\ VS2013 \ VC \包括\目錄 線:289
我覺得行談論的文件 「列表」 。
當它打破VS指向while循環條件,說它是下一行要執行。
什麼是確切的錯誤和它是什麼行? –
舊的「用迭代器循環時擦除迭代器」的困境。如果你只是使用std :: partition並對死船進行分區,然後在該循環之外刪除/擦除它們,那將更容易。如果您沒有使用dynamic_cast,而是使用適當的OO技術(如虛擬功能),它也會有所幫助。 – PaulMcKenzie
@PaulMcKenzie我們還沒有被教過分區,所以我不能使用它。另外,船隻不會死亡。只是導彈。 dynamic_cast真的會引起我所看到的問題嗎? – user3334986