问题描述
我有一个 vector 并且我在 vector 中放入了很多项目,我需要快速访问,所以我不使用 list.如何设置vector的初始大小(例如设置为20 000个位置,以免插入new时复制)?
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)?
推荐答案
std::vector<CustomClass *> whatever(20000);
或:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
前者设置数组的实际大小——即,使其成为一个包含 20000 个指针的向量.后者将向量留空,但为 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.
至少根据我的经验,这两者中的任何一个对性能产生巨大差异是相当不寻常的——但在某些情况下,任何一个都会影响正确性.特别是,只要不发生重新分配,向量中的迭代器就可以保证保持有效,并且一旦您设置了大小/保留空间,就可以保证只要您不重新分配就不会发生任何重新分配t 增加超过这个大小.
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.
这篇关于如何设置 std::vector 的初始大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)