表达式:向量下标超出范围

时间:2019-08-10 01:42:24

标签: c++ visual-studio sfml

我正在通过SFML制作简单的游戏,并且遇到了以下错误:

调试断言失败! 表达式:向量下标超出范围

此错误仅在“火箭”与第一个“敌人”接触而屏幕上同时有3个敌人时出现。我知道这与我要在for循环中从向量中删除元素有关,但是我能否获得关于为什么仅在屏幕上出现3个或更多敌人时才会发生此错误的明确答案。另外,如何重写代码,以便可以从敌人向量中删除“敌人”元素而不会引起错误?预先感谢

    for (int i = 0; i < rockets.size(); i++) //This is where the error points to
    {
        for (int j = 0; j < enemies.size(); j++)
        {
            Rocket *rocket = rockets[i];
            Enemy *enemy = enemies[j];

            if (checkCollision(rocket->getSprite(), enemy->getSprite()))
            {
                //hitSound.play();
                score++;
                std::string finalScore = "Score: " + std::to_string(score);
                scoreText.setString(finalScore);
                sf::FloatRect scoreBounds = scoreText.getGlobalBounds();
                scoreText.setOrigin(scoreBounds.width / 2, scoreBounds.height / 2);
                scoreText.setPosition(viewSize.x * 0.5f, viewSize.y * 0.10f);



                rockets.erase(rockets.begin() + i);
                enemies.erase(enemies.begin() + j);

                delete(rocket);
                delete(enemy);
                if (score % 5 == 0) levelUp();
                printf("rocket intersects with enemy \n");
            }
        }
    }

我已经将敌人和火箭物体存储在矢量中:

    std::vector <Enemy*> enemies;
    std::vector <Rocket*> rockets;

如果有帮助,这是我的整个更新功能:

void update(float dt)
{
    hero.update(dt);

    currentTime += dt;
    if (currentTime >= prevTime + 1.125f)
    {
        spawnEnemy();
        prevTime = currentTime;
    }

    for (int i = 0; i < enemies.size(); i++)
    {
        Enemy *enemy = enemies[i];
        enemy->update(dt);

        if (enemy->getSprite().getPosition().x < 0)
        {
            enemies.erase(enemies.begin() + i);
            delete(enemy);
            gameOver = true;
            gameOverSound.play();
        }
    }

    for (int i = 0; i < rockets.size(); i++)
    {
        Rocket *rocket = rockets[i];

        rocket->update(dt);

        if (rocket->getSprite().getPosition().x > viewSize.x)
        {
            rockets.erase(rockets.begin() + i);
            delete(rocket);
        }
    }

    for (int i = 0; i < rockets.size(); i++)
    {
        for (int j = 0; j < enemies.size(); j++)
        {
            Rocket *rocket = rockets[i];
            Enemy *enemy = enemies[j];

            if (checkCollision(rocket->getSprite(), enemy->getSprite()))
            {
            //hitSound.play();
                score++;
                std::string finalScore = "Score: " + std::to_string(score);
                scoreText.setString(finalScore);
                sf::FloatRect scoreBounds = scoreText.getGlobalBounds();
                scoreText.setOrigin(scoreBounds.width / 2, scoreBounds.height / 2);
                scoreText.setPosition(viewSize.x * 0.5f, viewSize.y * 0.10f);



                rockets.erase(rockets.begin() + i);
                enemies.erase(enemies.begin() + j);

                delete(rocket);
                delete(enemy);
                if (score % 5 == 0) levelUp();
                printf("rocket intersects with enemy \n");
            }
        }
    }

    for (int i = 0; i < enemies.size(); i++)
    {
        Enemy *enemy = enemies[i];

        if (checkCollision(enemy->getSprite(), hero.getSprite()))
        {
            gameOver = true;
            gameOverSound.play();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

  

此外,我该如何重写代码,以便删除“敌人”   敌人矢量中的元素而不会引起错误?

如果允许您更改RocketEnemy,则最简单的更改将是添加一个bool成员以表示该对象是存活的还是死亡的。然后,只需将对象标记为死,而无需实际从容器中删除该对象即可。然后,在循环之后,移除死掉的物体。

EnemyRocket类所需的更改将是添加一个bool成员,该成员指示是否需要删除该对象:

class Enemy
{
   bool destroyed;
   //...
   public:
        Enemy() : destroyed(false) {}
        bool is_destroyed() const { return destroyed; }
        void set_destroyed() { destroyed = true; }
};

class Rocket
{
   bool destroyed;
   //...
   public:
        Rocket() : destroyed(false) {}
        bool is_destroyed() const { return destroyed; }
        void set_destroyed() { destroyed = true; }
};

一旦完成更改,以下可能是主循环的代码更改:

#include <algorithm>
//...
for (int i = 0; i < rockets.size(); i++) 
{
    if ( rockets[i]->is_destroyed() )  // skip if this was destroyed
       continue;        
    for (int j = 0; j < enemies.size(); j++)
    {
        if (enemies[j]->is_destroyed())  // skip if this was destroyed
           continue;
        Rocket *rocket = rockets[i];
        Enemy *enemy = enemies[j];
        if (checkCollision(rocket->getSprite(), enemy->getSprite()))
        {
            //hitSound.play();
            score++;
            std::string finalScore = "Score: " + std::to_string(score);
            scoreText.setString(finalScore);
            sf::FloatRect scoreBounds = scoreText.getGlobalBounds();
            scoreText.setOrigin(scoreBounds.width / 2, scoreBounds.height / 2);
            scoreText.setPosition(viewSize.x * 0.5f, viewSize.y * 0.10f);

            // "destroy" these items
            rocket->set_destroyed();
            enemy->set_destroyed();

            if (score % 5 == 0) levelUp();
            printf("rocket intersects with enemy \n");
            break; // since the rocket is destroyed, 
        }
    }
}

// remove the dead items

// first partition the dead items off from the live items
auto iter = std::stable_partition(rockets.begin(), rockets.end(), [](rocket *r) 
                                  {return r->is_destroyed();});

// issue a delete call on these items.
std::for_each(rockets.begin(), iter, [](rocket *r) { delete r; });

// now erase from the container
rockets.erase(rockets.begin(), iter);

// do similar for the enemies container
auto iter2 = std::stable_partition(enemies.begin(), enemies.end(), [](enemy *e) 
                                  {return e->is_destroyed();});
std::for_each(enemies.begin(), iter2, [](enemy *e) { delete e; });
enemies.erase(enemies.begin(), iter2);

基本上,我们标记要销毁的物品,然后在循环完成后处理它们。我们处理它们的方法是使用std::stable_partition对死掉的项目进行分区,在分区左侧的每个项目上调用delete,最后从容器中删除它们。

我之所以不简单使用std::remove_if是因为remove_if算法使要删除的项目无效,因此尝试发出delete调用将导致未定义的行为。因此,首先将“死”项分开,然后delete-将它们分开,然后再将它们擦除,IMO会更安全。