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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With