简体   繁体   English

在 vector.push_back() 导致重新分配之后,如何让向量迭代器指向一个向量?

[英]How to get a vector iterator to point to a vector after vector.push_back() has caused reallocation?

I have a function void AddEntity(Entity* addtolist) that pushes elements back onto a vector but since the size and capacity are equal when the element is added to the vector , the vector reallocates and the iterator becomes invalid.我有一个 function void AddEntity(Entity* addtolist)将元素推回vector ,但由于将元素添加到vector时大小和容量相等,因此向量重新分配并且iterator变得无效。

Then when I try to increment the iterator I get a crash because of the invalid iterator, since push_back(...) doesn't return a iterator to the reallocated memory I was wondering how to get around this problem.然后,当我尝试增加迭代器时,由于无效的迭代器而崩溃,因为push_back(...)不会将迭代器返回到重新分配的 memory 我想知道如何解决这个问题。

Should I just use insert(...) since it does return an iterator , or should I use a pointer that stores the reference to the vector after its reallocated and then have the iterator equal the pointer that points to the reallocated vector ?我应该只使用insert(...) ,因为它确实返回了一个iterator ,还是应该使用一个指针来存储重新分配后对向量的引用,然后让iterator等于指向重新分配的vector的指针?

vector::push_back(const T& x);

Adds a new element at the end of the vector, after its current last element.在当前最后一个元素之后,在向量的末尾添加一个新元素。 The content of this new element is initialized to a copy of x.这个新元素的内容被初始化为 x 的副本。

This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the vector capacity before the call.这有效地将向量size增加一,如果向量大小等于调用前的向量容量,则会导致内部分配的存储重新分配。 Reallocations invalidate all previously obtained iterators, references and pointers.重新分配使所有先前获得的迭代器、引用和指针失效。

Using an invalidated vector is going to lead you to crashes or undefined behaviors.使用无效的向量会导致崩溃或未定义的行为。
So just get a new iterator by using vector::begin() .所以只需使用vector::begin()获得一个新的迭代器。

vector<int> myvector;

vector<int>::iterator it;
it=myvector.begin()

As @Als already answered, push_back() may invalidate all iterators if relocation takes place.正如@Als 已经回答的那样,如果发生重定位, push_back()可能会使所有迭代器无效。

Dependent on the problem you try solve, std::list may be what you need.根据您尝试解决的问题, std::list可能是您需要的。 Adding element to list doesn't invalidate existing iterators to the container.将元素添加到list不会使容器的现有迭代器无效。

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

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