Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing an "std::vector"; which elements are affected?

Tags:

c++

vector

resize

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?

like image 733
hkBattousai Avatar asked Jan 27 '11 19:01

hkBattousai


1 Answers

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

like image 69
fredoverflow Avatar answered Sep 18 '22 01:09

fredoverflow