简体   繁体   English

从向量C ++中移除时,向量迭代器不可解除

[英]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. 我想将必须删除的元素与最后一个元素交换,然后使用pop_back()避免在向量中间删除,但我始终认为我的迭代器不可取消引用,我不太明白为什么这样做一个问题。

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. find返回一个迭代器,该迭代器指向找到的元素(在您的情况下)是要删除的元素。 When you calculate pos , you get the index for the element right after the one that was found. 计算pos ,将在找到元素后立即获得该元素的索引。 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. 然后,为此计算迭代器时,您将获得无法取消引用的end迭代器。

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. 然后立即在if的正文中调用mEneities.pop_back() ,而不是在之后。 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. pop_back之外使用pop_back调用, if找不到要查找的元素,则将移除向量的最后一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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