作者:手机用户2502911617_428 | 来源:互联网 | 2023-05-18 14:25
我找不到任何可以给出明确答案的东西.我很好奇,如果std::vector只在绝对必须时重新分配其内部数组,或者它会在预期中提前重新分配(可以这么说).例如:std::vector
我找不到任何可以给出明确答案的东西.我很好奇,如果std :: vector只在绝对必须时重新分配其内部数组,或者它会在预期中提前重新分配(可以这么说).
例如:
std::vector myVector;
for (int i = 0; i <1000; ++i) myVector.push_back(i);
cout < <
如果我继续添加元素,我添加的其他24个项目之一是否有可能改变容量,或者只有在我放入第25个项目后它才会重新分配?
注意:
我在Linux下使用gcc 4.4.3进行了测试,但似乎重新分配是“按需”完成的,但我很好奇我是不是很幸运,或者有什么东西说明这是预期的行为.
解决方法:
从C标准23.2.4.2开始:
size_type capacity() const;
Returns: The total number of elements that the vector can hold without requiring reallocation.
也来自标准
Notes: Reallocation invalidates all the references, pointers, and iterators referring to the elements in the
sequence. It is guaranteed that no reallocation takes place during insertions that happen after a call to
reserve() until the time when an insertion would make the size of the vector greater than the size
specified in the most recent call to reserve().
所以,是的,你可以肯定.
编辑:正如@Bo Persson所说,有一个问题.如果我们从不调用reserve(),标准也没有说什么.但是在实践中它运行良好,因为如果你调用reserve,没有实现会记住.我相信这是错误.正如@Martin在他对C 0x草案的回答中提到的那样,它得到了纠正.