如何设置std :: vector的初始大小? [英] How to set initial size of std::vector?

查看:1176
本文介绍了如何设置std :: vector的初始大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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的初始大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆