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

标签 c++ list

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

这是我的代码:

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/

相关文章:

c++ - 检查 char 数组中前导字符的最快方法是什么?

string - 用于获取字符串中每个字符的 ASCII 码的 Tcl

python - 从python中的一个奇怪列表传递值

list - docx4j 创建未编号/项目符号列表

c++ - 需要帮助理解与 friend 声明有关的段落

c++:通过指针访问主类的std::vector的类出错

c++ - C++中的算术溢出添加了2个SWORD

c++ - 我的程序正在从字符串中删除一个字符,如何避免这种情况?

c# - 将对象列表转换为字符串和泛型列表

python - 需要以列表形式获取输出,而不是 Popen 或任何其他系统命令中的字符串