简体   繁体   中英

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.

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.

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 ?

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.

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. 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<int> myvector;

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

As @Als already answered, push_back() may invalidate all iterators if relocation takes place.

Dependent on the problem you try solve, std::list may be what you need. Adding element to list doesn't invalidate existing iterators to the container.

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