hkBattousai
hkBattousai

Reputation: 10911

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 vector with this code: vect.resize(3)?

Question 2 (Expanding): After expanded this vector by the code vect.resize(7);
a. Are the first 5 elements (0th through 4th) kept unchanged?
b. What happens to the newly added two elements (5th and 6th)? What are their default values?

Upvotes: 6

Views: 4186

Answers (4)

fredoverflow
fredoverflow

Reputation: 263098

Question 1: Yes, the standard says:

void resize(size_type sz);

If sz < size(), equivalent to erase(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().

Upvotes: 12

Jerry Coffin
Jerry Coffin

Reputation: 490098

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().

Upvotes: 1

templatetypedef
templatetypedef

Reputation: 372714

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.

Upvotes: 1

GWW
GWW

Reputation: 44093

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.

Upvotes: 1

Related Questions