How to set initial size of std::vector?(如何设置 std::vector 的初始大小?)
问题描述
我有一个 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 的初始大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何设置 std::vector 的初始大小?
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
