簡體   English   中英

C ++映射/設置迭代器不遞增錯誤

[英]C++ Map/Set iterator Not Incrementable Error

我一直在處理此錯誤已有一段時間,但不確定如何解決。

我有一個EntityManager來處理我正在開發的游戲中的所有實體,每個實體都添加到一個地圖中,該地圖按每個實體給出的隨機ID進行排序。

void EntityManager::AddEntity(Entity* entity)
{
    int ID = rand();
    for(int i = 0; i < IDS.size(); i++)
    {
        if(IDS[i] == ID)
        {
            ID = rand();
            i = 0;
        }
        else
        {
            break;
        }
}

entity->SetID(ID);
entities.insert(pair<int, Entity*>(ID, entity));

當我想刪除游戲中的實體時,我只需調用此RemoveEntity函數:

void EntityManager::RemoveEntity(Entity* entity)
{
    entities.erase(entity->GetID());
    delete entity;
}

並通常通過“ this”傳入要刪除的實體,如下所示:

virtual void Effect::RemoveEffect()
{
    DeleteEntity(this);
}

void DeleteEntity(Entity* entity)
{
    entityManager->RemoveEntity(entity);
}

順便說一句,游戲中的所有內容都從該Entity Class繼承。

我遇到的問題是當我調用“ RemoveEntity”函數並運行以下代碼行時發生的錯誤:

entities.erase(entity->GetID());

該游戲將僅因Map / Set迭代器“不可遞增的錯誤”而崩潰,我只是不知道為什么。 我看過其他有關出現此錯誤的人的話題,但解決問題的方法是通過對for循環進行更改,如您所見……我沒有。

我應該注意,盡管此錯誤僅在我以這種方式刪除實體時發生:

destroyTimer += deltaTime;
if(destroyTimer >= destroyDelay)
{
    entityManager->RemoveEntity(this);
}

我有一個計時器來延遲刪除實體的時間。 這部分代碼在GameLoop期間調用的Update Function中,因此每一幀。 當我只是立即調用“ RemoveEntity”函數而沒有上述任何計時器時,刪除Entity的過程不會出錯,但是我不明白為什么會導致錯誤。

有人知道發生了什么嗎?

編輯上面示例中顯示的RemoveEntity函數在每個實體具有的實體的Update函數中,完整的Update循環如下所示:

void PointEffect::Update(float deltaTime)
{
    Entity::Update(deltaTime);

    destroyTimer += deltaTime;
    if(destroyTimer >= destroyDelay)
    {
        RemoveEffect();
    }
}

Entity :: Update(deltaTime)只是調用它:

virtual void Update(float deltaTime)
{
    if(animationHandler != nullptr)
    {
        animationHandler->Update(deltaTime);            
    }

    if(moveSpeed != 0)
    {
        position += velocity * moveSpeed;
    }

    if(collision != nullptr)
    {
        collision->Update(GetSpriteRect(), position);
    }
}

在每個實體中找到的Update循環由實際的EntityManagers Update循環調用,然后由GameStates Update函數調用,而GameStates Update函數則由GameLoop本身調用。 EntityManager更新功能:

void EntityManager::Update(float deltaTime)
{
if(!entities.empty())
{
        for(const auto entity : entities)
        {           
             entity.second->Update(deltaTime);
        }
    }
}

GameState更新功能:

void MainGame::Update(float deltaTime)
{
    entityManager->Update(deltaTime);
}

EntityManager::Update中的for循環運行時,您不能從entities刪除entity 這是因為for循環仍在使用迭代器。 您需要記下在循環運行時要刪除的實體(然后刪除它們),或者使用傳統的for循環並將循環迭代器前進到下一個元素,然后再調用Update (僅當您只是不刪除其他實體)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM