调整“std::vector"的大小;哪些元素受到影响? [英] Resizing an "std::vector"; which elements are affected?
问题描述
std::vector向量;AClass Object0, Object1, Object2, Object3, Object4;vect.push_back(Object0);//第 0 个vect.push_back(Object1);//第一个vect.push_back(Object2);//第二vect.push_back(Object3);//第三vect.push_back(Object4);//第四
问题 1(收缩): 是否保证 0th、1st 和 2nd 元素受到保护(即;它们的值不会改变)在使用以下代码调整此向量的大小后:vect.resize(3)
?
问题2(扩展):通过代码vect.resize(7)
扩展这个向量后;
a.前 5 个元素(0th 到 4th)是否保持不变?
b. 新添加的两个元素(5th 和 6th)会发生什么变化?它们的默认值是什么?
问题 1:是的,标准说:
<块引用>void resize(size_type sz);
如果 sz
erase(begin() + sz, end());
.
问题 2:如果不需要调整大小,是的.否则,您的元素将被复制到内存中的不同位置.它们的值将保持不变,但这些值将存储在其他地方.所有对这些对象的迭代器、指针和引用都将失效.默认值为 AClass()
.
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?
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()
.
这篇关于调整“std::vector"的大小;哪些元素受到影响?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!