waas1919
waas1919

Reputation: 2605

C++ - Vector iterator not incrementable error

I have myVector with some values of the type Texture_Map which is just an int.

I'm not erasing anything... I just want to insert a value in each even iteration.

Something like: If I have this vector [1,2,3,4,5]

And my Texture_Map::TEXTURE_FLIP is 99, then my final vector should be:

[99,1,99,2,99,3,99,4,99,5]

After the first insert() I get the "Vector iterator not incrementable problem" error.

The code:

myVector.push_back(Texture_Map::TEXTURE_INIT);

for(unsigned int i = 0 ; i < m_max_pieces-2; i++)
    myVector.push_back((Texture_Map::TextureID)i);

std::random_shuffle(myVector.begin(), myVector.end());

std::vector<Texture_Map::TextureID>::iterator it = myVector.begin();

for (it=myVector.begin(); it<myVector.end(); it++)
{
    myVector.insert(it,Texture_Map::TEXTURE_FLIP);
}

Thanks!

Upvotes: 2

Views: 5483

Answers (1)

Barry
Barry

Reputation: 302852

As part of the consequence of using insert on a vector is that it:

Causes reallocation if the new size() is greater than the old capacity(). If the new size() is greater than capacity(), all iterators and references are invalidated. Otherwise, only the iterators and references before the insertion point remain valid. The past-the-end iterator is also invalidated.

The issue you're seeing is that you're attempting to increment an iterator which is no longer valid - it's past the insertion point, so it's invalidated. The solution here is to take advantage of that fact that insert returns an iterator:

iterator insert( iterator pos, const T& value );

Specifically:

Return value
1-2) Iterator pointing to the inserted value

So you want:

for (it=myVector.begin(); it<myVector.end(); it++) {
    // now it will point to TEXTURE_FLIP
    it = myVector.insert(it,Texture_Map::TEXTURE_FLIP);

    // now it will point back to the original element
    ++it;
}

Upvotes: 4

Related Questions