我找不到任何能给出明确答案的东西。我只是好奇 std::vector 是否仅在绝对必须或将在预期中提前重新分配时才重新分配其内部数组(可以这么说)。
例如:
std::vector<int> myVector;
for (int i = 0; i < 1000; ++i) myVector.push_back(i);
cout << myVector.size() << '\n' // Gives 1000 as expected
<< myVector.capacity() << endl; // Gives 1024 which makes sense
如果我继续添加元素,我添加的接下来的 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 草稿中的回答中提到的那样,它已得到纠正。
关于c++ - std::vector 何时重新分配其内存数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5410035/