如何在联系时从两个列表中删除元素?

时间:2017-04-20 07:30:43

标签: c++ list

我正在为一堂课编写Space Invaders非常困难。我应该使用一个列表存储我的“导弹”和一个列表来存储我的“外星人”。我按空格键加载一个新的外星人,当两个人联系时,我试图删除他们两个,我甚至无法删除“外星人”。当发射多个导弹时,我会遇到各种各样的错误,如果这个功能被注释掉,导弹工作正常。我被迫将一个导弹列表传递给另一个已经包含外星人列表的类并删除它们。

以下是有问题的代码:

bool AlienMgr::checkHit(PlayerMgr& playerMgr)
{

    bool hit = false; // If the player hits an alien, switches to true and is returned.
    list<Missile*>::iterator missileIter;
    list<Missile*> missileList = playerMgr.getMissiles();
    int missileCount;

    FloatRect missileBounds;
    FloatRect alienBounds;

    iter = myAliens.begin();

    while (!myAliens.empty() && iter != myAliens.end())
    {
        alienBounds = (*iter)->getGlobalBounds();

        if (!missileList.empty() && !hit)
        {

            for (missileIter = missileList.begin(); missileIter != missileList.end() && !hit; missileIter++)
            {
                missileBounds = (*missileIter)->getMissileBounds();

                if (alienBounds.intersects(missileBounds))
                {
                    delete (*iter);
                    iter = myAliens.erase(iter);
                    cout << "HIT" << endl;

                }
                else
                {
                    iter++;
                }
            }
        }
        else
        {
            iter++;
        }
    }
    return hit;
}

1 个答案:

答案 0 :(得分:0)

您的代码中存在多个问题。我试图清理它们。另外,我希望你能使用c ++ 11。

With CTE
AS
(
select *, ROW_NUMBER() over (partition by Consgno order by Consgno) as Number
from Test)

select * from CTE where Number = 2

然而,还有更多关键问题。你的代码太c ++ 98&#39; ish。 我会建议几项改进:

  • 使用bool AlienMgr::checkHit(PlayerMgr& playerMgr) { bool hit = false; // If the player hits an alien, switches to true and is returned. list<Missile*> missileList = playerMgr.getMissiles(); int missileCount; FloatRect missileBounds; FloatRect alienBounds; // iter == myAliens.end() if it's empty for (auto iter = myAliens.begin(); iter != myAliens.end();) { bool hitDetected = false; alienBounds = (*iter)->getGlobalBounds(); // remove all missiles intersecting current alien and set flag missileList.remove_if([&](Missile* missile) { if (!alienBounds.intersects(missile->getMissileBounds())) return false; hitDetected = true; delete missile; return true; }); if (hitDetected) { hit = true; delete (*iter); iter = myAliens.erase(iter); cout << "HIT" << endl; else { iter++; } } return hit; } 代替std::vector(当列表更快时,真的很难找到案例)
  • 使用智能指针代替手动内存管理(代码将更加简单易懂)