According to Stroustrup : The C++ programming language :-
“When a vector is resized to accommodate more (or fewer) elements, all of its elements may be
moved to new locations.”
Is this holds true, even if the vector is re-sized to smaller size ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Case 1: If the new size being requested is greater than the current
std::vector::capacity()then all elements will be relocated.Case 2: If the new size being requested is lesser than the current
std::vector::capacity()then there will be no relocation of elements.Standerdese Evidence:
The standard defines effect of
vector::resize()as:C++11 Standard 23.3.6.3/12 vector capacity:
Effect:
As @DavidRodríguez-dribeas correctly points out, Iterator invalidation rules for
std::vector::insert()operation are:Essentially this means:
All iterators and references before the point of insertion will be unaffected, unless the new container size is greater than the previous capacity because in such a scenario all elements might be moved to new locations thus invalidating pointers/iterators to original location.Since
resize()only erases/inserts elements at the end of the container[Note 1].The governing factor boils down to size being requested as against current capacity.Hence the Case 1 result.
In Case 2
std::vector::erase()will be called and the invalidation rule in this case is:Since [Note 1], elements will be only removed at end and there is no need of relocation of all elements.