矢量范围问题

Vector range issues

本文关键字:问题 范围      更新时间:2023-10-16

所以我试图创建一种保存/跳跃系统,玩家可以在其中将世界的某些方面恢复到前一点。由于某些原因,以下代码会产生矢量错误。("矢量下标超出范围")

(entityList是ptr,recordedEntityList不是)

void Map::record()
{
    for(unsigned int x = 0; x < entityList.size(); x++)
    {
        if(entityList[x]->getRewind() == true)
        {
            recordedEntityList.push_back(*entityList[x]);
            printf("%f, %fn", entityList[x]->getSprite().getPosition().x, entityList[x]->getSprite().getPosition().y);
        }
    }
}
void Map::rewind()
{
    for(unsigned int x = 0; x < entityList.size(); x++)
    {
        if(entityList[x]->getRewind() == true)
        {
            entityList.erase(entityList.begin() + x);
        }
    }
    for(unsigned int y = 0; y < recordedEntityList.size(); y++)
    {
        entityList.push_back(&recordedEntityList[y]);
    }
    recordedEntityList.clear();
}

rewind中,将指向recordedEntityList元素的指针推入entityList,然后清除recordedEntityList。这将导致entityList包含无效的指针,并在访问指针时调用未定义的行为。

此外,与此错误无关,在rewind的第一个循环中迭代向量时修改向量的方式可能会导致跳过条目:如果两个连续条目的getRewind()返回true,则第二个条目不会被删除。