Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
thatguyoverthere Avatar asked Jan 28 '26 12:01

thatguyoverthere


1 Answers

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()
like image 103
Alok Save Avatar answered Jan 30 '26 01:01

Alok Save