简体   繁体   中英

vector iterator not dereferencable when removing from vector C++

I have a vector with a large amount of elements that get created and delete continously.
I want to swap the element that has to be removed with the last element and then use pop_back() to avoid removing in the middle of a vector but I always get that my iterator is not dereferenceable and i don't quite get why this is an issue.

could someone explain what exactly is happening?

void EntityManager::RemoveEntity(Entity* entity)
{
    std::vector<Entity*>::iterator it = std::find(mEntities.begin(), mEntities.end(), entity);

    if (it != mEntities.end())
    {
        int pos = it - mEntities.begin() + 1;
        std::iter_swap(mEntities.begin() + pos, mEntities.end()-1);
    }
        mEntities.pop_back();
}

This part:

int pos = it - mEntities.begin() + 1;

is not needed. All you need to do is this:

if (it != mEntities.end())
    std::iter_swap(it, mEntities.end() - 1);

The find returns an iterator that points to the found element, which (in your case) is the element you want to remove. When you calculate pos , you get the index for the element right after the one that was found. If the found element is the last element in the vector, this will refer to the one-past-the-end element. When you then calculate the iterator for that, you'll get the end iterator, which you cannot dereference.

You don't need to calculate the index. Just call

std::swap(*it, m_Entities.back());

then immediately call mEneities.pop_back() within the body of the if , not after. With the pop_back call outside the if , you'll remove the last element of the vector if the element you're looking for was not found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM