Consider this piece of code:
Uint counter = 0;
int* p1;
int* p2;
deque<int> dequeInstance;
vector<int> vectorInstance;
dequeInstance.push_back(3);
dequeInstance.push_back(7);
p1 = &dequeInstance.back();
dequeInstance.push_back(17);
p2 = &dequeInstance.back();
if(*p1 == !7)
++counter;
if(*p2 == !17)
++counter;
vectorInstance.push_back(3);
vectorInstance.push_back(7);
p1 = &vectorInstance.back();
vectorInstance.push_back(17);
p2 = &vectorInstance.back();
if(*p1 == !7)
++counter;
if(*p2 == !17)
++counter;
return counter;
I would have expected that when I pushed the third element to the back of the vector, the pointer to the second element would have been invalidated, as my understanding of std::vector is that its a straight array which is wiped and recreated every time its modified. By the end of this code however ‘counter’ is equal to zero.
What am I missing here?
Hopefully for performance,
std::vectoris not ‘wiped and recreated every time it’s modified’.A vector has a
capacitywhich may exceed itssize, which means that it can allocate more memory than truly used. When youpush_back, a reallocation will only occur if the new size is greater than the old capacity, and in this case, iterators are invalidated.In your case, you should check the value of
capacityright after thestd::vectorinstantiation. You will see that it’s without any doubt greater than 3, thus, none of yourpush_backcalls trigger a reallocation and all iterators remain valid.Also note that
std::vectorprovides areservemember function which allow you to control the vector capacity. This is really useful when you know how many elements are expected to be inserted in order to avoid ulterior reallocation.