简体   繁体   English

用迭代器插入向量

[英]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()). 我不能使用insert()函数(我已经获得了明确的指导方针,我应该在没有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. 如此看来,我的调整大小弄乱了迭代器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. 您可以组合std::vector::push_back在后面插入新元素,然后从<algorithm>插入std::rotate rotate将最后一个元素旋转到所需位置。

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. 当然push_back不会保留迭代器,因此请首先使用std::distance(v.begin(), it) (来自<iterator> )来确定所需位置的索引。

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. Stardard程序将首先检查是否需要调整大小,然后在可选的调整大小操作之后,以所需的任何方式继续插入新元素。

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. 在调用resize()pos不是有效的迭代器,应再次将其重新分配给wb.begin()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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