简体   繁体   中英

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();

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.

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.

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.

听起来,本练习的目的是教您关于迭代器无效的知识 ,因此您应该问自己的问题是:“是否有等效于迭代器且不会失效的等效项?”

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM