如何设置std的初始大小::向量?

时间:2022-11-21 14:50:30

I have a vector<CustomClass*> and I put a lot of items in the vector and I need fast access, so I don't use list. How to set initial size of vector (for example to be 20 000 places, so to avoid copy when I insert new)?

我有一个向量 我在向量中放了很多项,我需要快速访问,所以我不使用list。如何设置向量的初始大小(例如为2万个位置,以便在插入新向量时避免复制)? *>

2 个解决方案

#1


105  

std::vector<CustomClass *> whatever(20000);

or:

或者:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

前者设置数组的实际大小——即。,使它成为一个有20000个指针的向量。后者使向量为空,但保留20000个指针的空间,因此您可以插入(最多)那么多,而不必重新分配。

You should probably be aware that chances of this doing any real good are minimal though.

你可能应该意识到,这样做真正有益的可能性很小。

#2


9  

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

您需要使用reserve函数来设置初始分配的大小,或者在初始构造函数中进行设置。

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

当您保留()元素时,向量将分配足够的空间给(至少?)那么多元素。元素不存在于向量中,但是内存已经准备好使用了。这可能会加速push_back(),因为内存已经分配了。

#1


105  

std::vector<CustomClass *> whatever(20000);

or:

或者:

std::vector<CustomClass *> whatever;
whatever.reserve(20000);

The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.

前者设置数组的实际大小——即。,使它成为一个有20000个指针的向量。后者使向量为空,但保留20000个指针的空间,因此您可以插入(最多)那么多,而不必重新分配。

You should probably be aware that chances of this doing any real good are minimal though.

你可能应该意识到,这样做真正有益的可能性很小。

#2


9  

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

您需要使用reserve函数来设置初始分配的大小,或者在初始构造函数中进行设置。

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

当您保留()元素时,向量将分配足够的空间给(至少?)那么多元素。元素不存在于向量中,但是内存已经准备好使用了。这可能会加速push_back(),因为内存已经分配了。