C ++中向量的初始容量
使用默认的constuctor创建的 std :: vector
的 capacity()
是什么?我知道 size()
是零。我们可以声明一个默认构造的向量不会调用堆内存分配?
What is the capacity()
of an std::vector
which is created using the default constuctor? I know that the size()
is zero. Can we state that a default constructed vector does not call heap memory allocation?
这样就可以使用单个分配创建一个任意保留的数组,比如 std :: vector< int> iv; iv.reserve(2345);
。让我们说,由于某种原因,我不想在2345上启动 size()
。
This way it would be possible to create an array with an arbitrary reserve using a single allocation, like std::vector<int> iv; iv.reserve(2345);
. Let's say that for some reason, I do not want to start the size()
on 2345.
,在Linux上(g ++ 4.4.5,内核2.6.32 amd64)
For example, on Linux (g++ 4.4.5, kernel 2.6.32 amd64)
#include <iostream>
#include <vector>
int main()
{
using namespace std;
cout << vector<int>().capacity() << "," << vector<int>(10).capacity() << endl;
return 0;
}
印刷 0,10
。这是一个规则,还是STL供应商的依赖?
printed 0,10
. Is it a rule, or is it STL vendor dependent?
标准没有指定初始 capacity
应该是,所以你依赖于实现。一个常见的实现将启动容量为零,但不能保证。另一方面,没有办法更好地你的策略 std :: vector< int> iv; iv.reserve(2345);
因此坚持下去。
The standard doesn't specify what the initial capacity
of a container should be, so you're relying on the implementation. A common implementation will start the capacity at zero, but there's no guarantee. On the other hand there's no way to better your strategy of std::vector<int> iv; iv.reserve(2345);
so stick with it.