在循环遍历向量时向向量添加 object

Adding an object to a vector whilst looping through it

我的 "Level" class 中有一个向量 GameObject*

vector<GameObject*> gameObjects;

我像这样向 Vector 添加一个 object:

gameObjects.push_back(new Laser(10, 30));

其中 Laser 是 child class 的 GameObject。然后我像这样遍历它们:

void Level::update() 
{
    for(vector<GameObject*>::const_iterator i = gameObjects.begin(); i != gameObjects.end(); ++i) {
        (*i)->update();
    }
}

其中 void update() 是 class GameObject 的成员函数。现在我可能会更新一个 object,比如 "gun",它会在它的过程中创建另一个 object,比如 "bullet",就像这样:

level.gameObjects.push_back(new Bullet(position, rotation));

其中 level 是 "Level" class 的实例。这行代码只用于查找,但在 "frame" 的末尾,当 level.update() 完成对现有 GameObject 的循环时,它崩溃了。这发生在它退出 for 循环之前。

为什么它会崩溃,我该如何解决这个问题?

向矢量添加新项目可能需要重新分配,如果新 size would exceed the capacity. When this happens, the iterators are invalidated

可能的解决方案:

  • 使用索引迭代以直接访问向量元素(最简单的解决方案)
  • 确保在开始使用迭代器之前 reserved 有足够的容量(并非总是可行)。