Resize "std :: vector"; which elements are affected?
std::vector<AClass> vect; AClass Object0, Object1, Object2, Object3, Object4; vect.push_back(Object0); // 0th vect.push_back(Object1); // 1st vect.push_back(Object2); // 2nd vect.push_back(Object3); // 3rd vect.push_back(Object4); // 4th Question 1 (Abbreviation): It is guaranteed that the 0th, 1st and 2nd elements are protected (i.e. their values do not change) after resizing this vector with this code: vect.resize(3) ?
Question 2 (Extension): After expanding this vector with vect.resize(7) ; a. Are the first 5 items saved (from 0 to 4)?
b. What happens to the recently added two elements (5th and 6th)? What are their default values?
Question 1: Yes, the standard says:
void resize(size_type sz);If
sz < size(), equivalent toerase(begin() + sz, end());.
Question 2: If resizing is not required, yes. Otherwise, your items will be copied to another location in memory. Their values will remain unchanged, but these values will be stored somewhere else. All iterators, pointers, and references to these objects will be invalidated. The default value is AClass() .
Question 1:
Yes, from cplusplus.com "If sz is smaller than the current size of the vector, the content is reduced to its first sz-elements, rest is discarded."
Question 2:
a) The first elements are kept unchanged, the vector simply increases the size of the internal buffer to add new elements.
b) The default constructor of the AClass class is called to insert each new element.
the vector always grows and contracts at the end, so if you reduce the size of the vector, only the last elements are deleted. If you grow a resize vector, new elements are added to the end, using the default object as the value for new records. For a class, this is the value of a new object created with standard constructors. For the primitive, this value is zero (or false for bool).
And yes, items that are not deleted are always protected during resizing.
Yes, when you shorten a vector, all remaining objects retain their previous values.
When you deploy a vector, you specify a parameter that determines the value that will be used to fill new slots. This parameter defaults to T() .