Erasing elements from the vector container

Hi all. I know how to erase / remove elements from the vector, but don't really know what's going on;

std::vector<Entity*> entities;

//adding :
void addEntity(Entity* entity){
entities.push_back(entity);
}

//removing
void removeEntity(Entity* entity){
for(auto it = entities.begin(); it != entities.end();)
if(*it == entity)
it = entities.erase(it);
else it++;

}


Why can't I increment the iterator in the loop statement, why do have to do it within the body itself?
And why do have to initialize 'it' to 'entities.erase(it)'?
Last edited on
When you erase an element all iterators to that element (and to all elements that follow) gets invalidated and should no longer be used. This means you need to assign a new valid iterator value to it before you continue iterating, so that's why you assign it to the return value of erase which is an iterator to the element that comes after the erased element.

So after you have erased an element it will already be referring to the element that you want to use in the next iteration, so that's why you don't want to do it++ when you have just erased an element, because that would skip one element (even worse if you're at the end).
Last edited on
Topic archived. No new replies allowed.