C ++向量的初始容量
我有一些使用数千个向量的代码,每个向量只有4个条目,因此我想将每个向量的初始大小设置为4,以便通过不保留未使用的内存来优化内存使用。
I have some code which uses thousands of vectors each vector has only 4 entries, So I want to set the initial size of each vector to 4 so that I can optimize memory usage by not reserving unused memory.
我尝试了保留方法:
vector<Foo> bar;
bar.reserve(10);
但似乎它在扩展而不在收缩,似乎也没有构造函数创建带有
but seems it expands and doesn't shrink, seems there also no constructor that creates a vector with a specified capacity.
还有2个额外的问题:
默认的初始容量是多少
我可以创建具有特定容量的矢量吗?
Can I create a vector with a specific capacity?
向量的容量不能由构造函数控制-没有适用的重载。
The capacity of a vector cannot be controlled by the constructors - there is no applicable overload.
C ++标准不能保证默认构造函数的容量。向量 vector< Foo>酒吧;
。但是,所有众所周知的实现都使用0作为默认容量。这是您可以依靠的东西,因为那时分配内存根本没有意义。
The C++ standard doesn't give any guarantee about the capacity of a default-constructed vector vector<Foo> bar;
. However all well-known implementations use 0 as the default capacity. This is something you can rely on, as allocating memory at that point just doesn't make sense.
所以我相信您的答案问题是:只需使用
So I believe the answer to your question is: just use
vector<Foo> bar;
bar.reserve(4);