gpt4 book ai didi

c++ - 无法删除 C++ 中的列表元素

转载 作者:行者123 更新时间:2023-11-28 05:07:26 27 4
gpt4 key购买 nike

我正在开发一个小游戏,遇到了一个关于列表的大问题。

这是我的代码:

void cCollisionManager::checkCollision(cPlayer * pPlayer, std::list<cAsteroid*> *asteroidList, std::list<cShot*> *ShotList)
{
sf::FloatRect PlayerBox = pPlayer->getSprite()->getGlobalBounds();

for (auto it : *asteroidList) {
for (auto es : *ShotList) {
sf::FloatRect asteroidboundingBox = it->getSprite()->getGlobalBounds();
sf::FloatRect ShotBox = es->getSprite().getGlobalBounds();

if (asteroidboundingBox.intersects(ShotBox)) {

it = asteroidList->erase(it);

*pPlayer->pPunkte += 1;
std::cout << *pPlayer->pPunkte << std::endl;
}

if (asteroidboundingBox.intersects(PlayerBox)) {
if (*pPlayer->phealth >= 0.f)
*pPlayer->phealth -= 0.5f;
}
}
}
}

我使用了 SFML,基本上一切正常。但是如果我想删除碰撞的小行星和镜头,程序会以错误退出。在 if 循环中,我试图删除对象,但编译器也给出了一个错误,指出参数类型与我给它的对象类型不同。

编辑我又看了一眼你推荐给我的另一个问题,但我仍然没有找到解决这个问题的方法。因此,如果我将代码更改为 while 循环,游戏将无法处理它,因为在 SFML 主循环的每次调用中实际上都会调用碰撞管理器。所以它只会卡在我的碰撞循环中。所以我稍微更改了我的代码,但仍然无法正常工作。

最佳答案

Don't modify sequences that are being enumerated with range-for. Use iterators and the appropriate result of an erase. – WhozCraig

这其实就是它的答案。我犯了错误 - 使用 for 循环而不是 while 循环,所以我的代码遇到了一些大问题和糟糕的构造想法 - 幸运的是现在一切正常!这是我的最终代码:

    auto it = asteroidList->begin();
auto es = ShotList->begin();

while (it != asteroidList->end()) {

sf::FloatRect PlayerBox = pPlayer->getSprite()->getGlobalBounds();
sf::FloatRect asteroidboundingBox = (*it)->getSprite()->getGlobalBounds();

while (es != ShotList->end())
{
sf::FloatRect ShotBox = (*es)->getSprite().getGlobalBounds();

if (asteroidboundingBox.intersects(ShotBox)) {
it = asteroidList->erase(it);
es = ShotList->erase(es);

std::cout << "Asteroid destroyed" << std::endl;
*pPlayer->pPunkte += 1;
std::cout << *pPlayer->pPunkte << std::endl;
}


if (es != ShotList->end())
es++;

}
if (asteroidboundingBox.intersects(PlayerBox))
{
if (*pPlayer->phealth > 3.f) {
*pPlayer->phealth -= 5.f;
it = asteroidList->erase(it);
}
else
*pPlayer->pBStateAlive = false;
}


if (it != asteroidList->end()) {
it++;
es = ShotList->begin();

}


}

关于c++ - 无法删除 C++ 中的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358965/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com