Why is this vector iterator not incrementable?

erase invalidates the iterator. You can’t use it any more. Luckily for you, it returns an iterator that you can use:

vector <Base*>::iterator deleteIterator = m_basesVector.begin();
while (deleteIterator != m_basesVector.end()) {
    deleteIterator = m_basesVector.erase(deleteIterator);
}

Or:

m_basesVector.clear();

Are you responsible for freeing the memory referred to by the pointers in the vector? If that’s the reason that you’re iterating (and your real program has more code that you haven’t shown, that frees those objects in the loop), then bear in mind that erasing from the beginning of a vector is a slow operation, because at each step, all the elements of the vector have to be shifted down one place. Better would be to loop over the vector freeing everything (then clear() the vector, although as Mike says that’s not necessary if the vector is a member of an object that’s being destroyed).

Leave a Comment