Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this vector iterator not incrementable?

Tags:

I'm trying to delete the vector's content and I'm getting an error - vector iterator is not incrementable, why is that?

This is my destructor:

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

thanks.

like image 996
Roy Gavrielov Avatar asked Sep 23 '10 14:09

Roy Gavrielov


People also ask

How do you access a vector element with iterator?

You need to make use of the begin and end method of the vector class, which return the iterator referring to the first and the last element respectively. using namespace std; vector<string> myvector; // a vector of stings. // push some strings in the vector. myvector. push_back("a"); myvector.

Can you dereference an iterator?

Dereferencing: An input iterator can be dereferenced, using the operator * and -> as an rvalue to obtain the value stored at the position being pointed to by the iterator. 4. Incrementable: An input iterator can be incremented, so that it refers to the next element in the sequence, using operator ++().

Does std :: move invalidate iterators?

For reference, std::vector::swap does not invalidate iterators.

What is the type of vector iterator?

The main iterators in C++ are Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random-Access Iterator. The C++ standard library has some function templates that use these iterators.


2 Answers

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).

like image 138
Steve Jessop Avatar answered Oct 23 '22 21:10

Steve Jessop


The problem is that you are trying to use an iterator while using the erase() function. erase(), push_back(), insert(), and other modifying functions invalidate iterators in STL.

Just use the clear() function:

City::~City()
{
    m_basesVector.clear();
}  
like image 44
riwalk Avatar answered Oct 23 '22 21:10

riwalk