Resizing an "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 (Shrinking): Is it guarantied that the 0th, 1st and 2nd elements are protected (i.e.; their values do not change) after resizing this ve开发者_StackOverflow社区ctor with this code: vect.resize(3)
?
Question 2 (Expanding): After expanded this vector by the code vect.resize(7)
;
Question 1: Yes, the standard says:
void resize(size_type sz);
If
sz < size()
, equivalent toerase(begin() + sz, end());
.
Question 2: If no resizing is required, yes. Otherwise, your elements will be copied to a different place in memory. Their values will remain unchanged, but those values will be stored somewhere else. All iterators, pointers and references to those objects will be invalidated. The default value is AClass()
.
Question 1:
Yes, from cplusplus.com "If sz is smaller than the current vector size, the content is reduced to its first sz elements, the rest being dropped."
Question 2:
a) The first elements are kept unchanged, the vector just increases the size of it's internal buffer to add the new elements.
b) The default constructor of AClass is called for the insertion of each new element.
vector always grows and shrinks at the end, so if you reduce the size of a vector only the last elements are removed. If you grow a vector with resize, new elements are added onto the end using the a default-constructed object as the value for the new entries. For a class, this is the value of a new object created with the default constructormas. For a primitive, this is zero (or false for bool).
And yes, elements that aren't removed are always protected during a resize.
Yes, when you shrink a vector, all the objects that remain retain their prior values.
When you expand a vector, you supply a parameter specifying a value that will be used to fill the new slots. That parameter defaults to T()
.
精彩评论