Johan Hjalmarsson
Johan Hjalmarsson

Reputation: 3493

insert into a vector with iterator

I have to insert elements on a specific position in a vector using iterator. I can NOT use the insert() function (I have gotten clear guidelines that I'm supposed to do it without insert()).

this is my code (or at least the part that messes up):

cerr << "distance before resize: " << distance(wl.begin(), pos) << endl;
wl.resize(wl.size()+1);
cerr << "distance after resize: " << distance(wl.begin(), pos) << endl;
move_backward(pos, wl.end()-1, wl.end());
(*pos) = temp;

my output:

distance before resize: 0
distance after resize: -322

so apperantly, my resize messes up the iterator pos. Any ideas on how to fix this?

edit: You might wanna know how I declare my iterator:

auto pos = wl.begin();

Upvotes: 0

Views: 447

Answers (4)

Rick Yorgason
Rick Yorgason

Reputation: 1666

It sounds like the intent of this exercise is to teach you about iterator invalidation, so the question you should be asking yourself is "Is there any equivalent to an iterator that doesn't get invalidated?"

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477040

You can combine std::vector::push_back to insert the new element at the back, followed by std::rotate from <algorithm> to rotate the last element into the desired position.

Of course push_back does not preserve iterators, so use std::distance(v.begin(), it) first (from <iterator>) to determine the index of the desired position.

Upvotes: 1

slaphappy
slaphappy

Reputation: 6999

Resizing a vector invalidates its iterators. After the call to resize(), pos is not a valid iterator and should be reassigned to wb.begin() again.

Upvotes: 0

blue
blue

Reputation: 2793

Resize cannot preserve the iterator since the resizing operation might invalidate the very content the iterator points to.

Stardard procedure would be to check if you need a resize first, and after the optional resizing operation you proceed with inserting new elements in whatever way you want.

Upvotes: 0

Related Questions