什么时候std :: vector重新分配它的内存数组? [英] When does a std::vector reallocate its memory array?
问题描述
我找不到任何给出确定答案的东西。我只是好奇,如果一个std :: vector重新分配它的内部数组,只有当它绝对必须或将重新分配时间预期(可以这么说)。
I can't find anything that gives a definitive answer. I was just curious if a std::vector reallocate its internal array only when it absolutely must or will it reallocate ahead of time in anticipation (so to speak).
示例:
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
如果我继续添加元素,
If I continue to add elements, is there ever any chance that one of the next 24 items I add will change the capacity or will it only reallocate once I put in a 25th item?
注意:
我在Linux下使用gcc 4.4.3运行了一个测试,但是似乎重新分配是按需完成的,但是我很好奇,如果我只是幸运的,或者有什么地方说
I did run a test using gcc 4.4.3 under Linux, but and it seems like the reallocation is done "on-demand", but I was curious if I was just lucky or if there is something somewhere stating that this is expected behavior.
推荐答案
从C ++标准23.2.4.2开始:
From C++ standard 23.2.4.2:
size_type capacity() const;
返回:向量可以容纳的元素总数,重新分配。
Returns: The total number of elements that the vector can hold without requiring reallocation.
也来自标准
注意:重新分配使引用
序列中的元素的所有引用,指针和迭代器无效。在调用
reserve()之后发生的插入期间,保证不会发生重新分配,直到插入将使向量的大小大于$ b $
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().
是的,你可以肯定。
编辑:由于@ Persson提到有一个catch。如果我们从不调用 reserve()
,标准不会说任何东西。然而在实践中它工作得很好,因为没有实现会关心记住,如果你叫储备,或不。我相信这是bug。正如@Martin在他的答案C ++ 0x草案中提到的,它被更正。
As @Bo Persson mentioned there is a catch. Standard doesn't say anything if we never call reserve()
. However in practice it works well, because no implementation will care to remember if you called reserve, or not. I believe that this is bug. And as @Martin mentioned in his answer in C++0x draft it is corrected.
这篇关于什么时候std :: vector重新分配它的内存数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!