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

2022-01-07 00:00:00 c++ stl

我有一个 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.

相关文章