简体   繁体   English

在“插入”向量后重用迭代器

[英]Re-using iterator after 'insert' into vector

I need some clarification regarding vector and iterator. 我需要对向量和迭代器进行一些说明。 I have a vector of my_object , and an iterator for that vector. 我有一个向量my_object ,以及该向量的迭代器。 I perform an insert at the iterator position, and a second insert at the same location: 我在迭代器位置执行插入,然后在同一位置执行第二次插入:

myiteratornew = (my_vector).insert(myiterator, my_object1);
myiteratornew = (my_vector).insert(myiterator, my_object2);

After using several times this function on several kind of 'input' data, today I get a memory error. 在几种类型的“输入”数据上使用此函数几次后,今天出现了内存错误。 Of course I think the problem is caused by the use of the old iterator on the modified (reallocated) vector; 当然,我认为问题是由在修改的 (重新分配的)向量上使用旧的迭代器引起的。 modifying the code this way now it works: 现在以这种方式修改代码即可:

myiteratornew = (my_vector).insert(myiterator, my_object1);
myiteratornew = (my_vector).insert(myiteratornew , my_object2);

My question is, how is it possible that I used my code several times without getting the memory error? 我的问题是,怎么可能多次使用我的代码而又没有出现内存错误? Should the second code prevent my code causing a memory error? 第二个代码应该防止我的代码引起内存错误吗?

If inserting a value into the vector will cause its size to become bigger that its capacity, a reallocation will happen. 如果在向量中插入值将导致其大小变得大于其容量,则会发生重新分配。 In this case, all iterators and references are invalidated. 在这种情况下,所有迭代器和引用均无效。

Otherwise, only the iterators and references before the insertion point remain valid. 否则,只有插入点之前的迭代器和引用保持有效。 The iterators and references after the insertion point, as well as past-the-end iterator are invalidated as well. 将插入点之后的迭代器和引用,以及past-the-end迭代器失效,以及。

That is most likely what happens to you - you are trying to use an iterator that is no longer valid. 这很可能发生在您身上-您正在尝试使用不再有效的迭代器。 That is also why your second example is working as expected - getting a new iterator, and inserting by it is the exactly right thing to do. 这就是为什么您的第二个示例按预期工作的原因-获得一个新的迭代器,并通过它插入是完全正确的事情。

What you are supposed to do is insert all objects at once. 您应该做的是一次插入所有对象。 The iterator is invalid afterwards, but since you inserted everything already you don't need it anymore. 此后迭代器无效,但是由于您已经插入了所有内容,因此不再需要它。 Also it is more efficient, since you need to move the objects behind the iterator only once and not multiple times. 另外,由于只需要将对象移动到迭代器后面,而无需多次移动,因此效率更高。

my_vector.insert(myiterator, begin(my_objects), end(my_objects));

In case your objects are not in a container you can put them there: 如果您的对象不在容器中,则可以将它们放在其中:

my_object1;
my_object2;

std::reference_wrapper<decltype(my_object1)> myobjects[] = {my_object1, my_object2};

使用std::list而不是std::vector可以使您免于获得内存错误。

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

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