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 aroun开发者_如何转开发d 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.
精彩评论