通过循环擦除向量中的数据导致断点

时间:2017-01-27 14:54:06

标签: c++ visual-studio sfml

我有一个类对象(项目符号)的向量,它在大多数情况下都有效。但是一旦我尝试删除子弹,它就会循环回来然后导致断点。 “基本的game.exe已经触发了一个断点。”我试过向后和向后迭代,但总是卡住了。

我正在使用SFML,对象是具有位置,旋转和大小的矩形。

    for (it = bullets.end(); it != bullets.begin(); it--)
    {
        it->draw(game); 
        it->move();
        if (it->bullet.getPosition().x > 800)
        {
            bullets.erase(it);
        }
    }

我是编码的菜鸟,所以如果你需要其他信息,请尝试提供它。

2 个答案:

答案 0 :(得分:4)

在向量上调用erase()时,迭代器变为无效。 相反,请考虑尝试:

 for (auto it = bullets.begin(); it != bullets.end();)
 {
    it->draw(game); 
    it->move();
    if (it->bullet.getPosition().x > 800)
    {
      it = bullets.erase(it);
    }
    else
    {
      it++;
    }
  }

答案 1 :(得分:3)

您可以使用

修复循环
for (auto& bullet : bullets) {
    bullet.draw(game);
    bullet.move();
}
bullets.erase(std::remove_if(bullets.begin(), bullets.end(),
                             [](const auto& bullet) {
                                 return bullet.getPosition().x > 800;
                             }),
              bullets.end());