C++ 如何设置 std::vector 的初始大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11457571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set initial size of std::vector?
提问by Damir
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)?
我有一个vector<CustomClass*>
,我在向量中放置了很多项目,我需要快速访问,所以我不使用列表。如何设置向量的初始大小(例如为 20 000 个位置,以避免在插入新时复制)?
回答by Jerry Coffin
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 个指针保留空间,因此您可以插入(最多)那么多而不必重新分配。
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
至少根据我的经验,其中任何一个在性能上产生巨大差异是相当不寻常的——但在某些情况下,任何一个都会影响正确性。特别是,只要不发生重新分配,向量中的迭代器就可以保证保持有效,并且一旦您设置了大小/保留空间,就可以保证只要您不重新分配就不会发生任何重新分配t 增加超出此范围的大小。
回答by Damir
You need to use the reserve function to set an initial allocated size or do it in the initial constructor.
您需要使用保留函数来设置初始分配大小或在初始构造函数中进行。
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.
当您创建reserve()
元素时,vector
将为(至少?)那么多元素分配足够的空间。元素不存在于 中vector
,但内存已准备好使用。这可能会加快速度,push_back()
因为内存已经分配。