在向量::resize()和向量::reserve()之间进行选择
我正在为我的 vector
数据成员预先分配一些内存。示例:
class A {
vector<string> t_Names;
public:
A () : t_Names(1000) {}
};
在某个时间点,如果 t_Names.size()
等于 1000
,我打算将大小增加 100
。一旦达到 1100
,就增加 100
,依此类推。
我应该从 vector::resize()
和 vector::reserve()
中选择哪一个?在这种情况下还有更好的选择吗?
编辑:我对t_Names
有一定的精确估计。我估计大约在 700
到 800
之间。然而,在某些(很少)情况下,它可以增长超过1000
。
I am pre-allocating some memory to my a vector
data member. Example:
class A {
vector<string> t_Names;
public:
A () : t_Names(1000) {}
};
At some point in time, if the t_Names.size()
equals 1000
, I intend to increase the size by 100
. Once it reaches 1100
, increase it by 100
and so on.
Which do I choose out of vector::resize()
and vector::reserve()
? Is there any better choice in this kind of scenario?
Edit: I have sort of precise estimate for the t_Names
. I estimate it to be around 700
to 800
. However in certain (seldom) situations, it can grow more than 1000
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这两个函数做的事情截然不同!
resize()
方法(将参数传递给构造函数等效于)将向向量插入或删除适当数量的元素以使其达到给定大小(它有可选的第二个参数来指定它们的值)。它将影响size()
,迭代将遍历所有这些元素,push_back 将在它们之后插入,您可以使用operator[]
直接访问它们。reserve()
方法仅分配内存,但未初始化。它仅影响capacity()
,但size()
将保持不变。对象没有任何价值,因为没有任何内容添加到向量中。如果您随后插入元素,则不会发生重新分配,因为它是提前完成的,但这是唯一的效果。所以这取决于你想要什么。如果您想要一个包含 1000 个默认项目的数组,请使用
resize()
。如果您想要一个要插入 1000 个项目的数组并希望避免多次分配,请使用reserve()
。编辑: Blastfurnace 的评论让我再次阅读了问题并意识到,在您的情况下,正确的答案是不要手动预分配。只需根据需要在末尾插入元素即可。该向量将根据需要自动重新分配,并且比提到的手动方式更高效。
reserve()
唯一有意义的情况是当您对需要轻松提前获得的总大小有相当精确的估计时。编辑2:广告问题编辑:如果您有初步估算,则
reserve()
该估算。如果结果还不够,就让向量来做它的事情。The two functions do vastly different things!
The
resize()
method (and passing argument to constructor is equivalent to that) will insert or delete appropriate number of elements to the vector to make it given size (it has optional second argument to specify their value). It will affect thesize()
, iteration will go over all those elements, push_back will insert after them and you can directly access them using theoperator[]
.The
reserve()
method only allocates memory, but leaves it uninitialized. It only affectscapacity()
, butsize()
will be unchanged. There is no value for the objects, because nothing is added to the vector. If you then insert the elements, no reallocation will happen, because it was done in advance, but that's the only effect.So it depends on what you want. If you want an array of 1000 default items, use
resize()
. If you want an array to which you expect to insert 1000 items and want to avoid a couple of allocations, usereserve()
.EDIT: Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocate manually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it more efficiently than the manual way mentioned. The only case where
reserve()
makes sense is when you have reasonably precise estimate of the total size you'll need easily available in advance.EDIT2: Ad question edit: If you have initial estimate, then
reserve()
that estimate. If it turns out to be not enough, just let the vector do it's thing.resize()
不仅会分配内存,还会创建与您传递给resize()<的所需大小一样多的实例< /code> 作为参数。但是reserve()只分配内存,不创建实例。也就是说,
输出(在线演示):
所以
resize()
可能不是如果您不想要默认创建的对象,则这是可取的。它也会很慢。此外,如果你push_back()
向它添加新元素,向量的size()
将通过分配新内存进一步增加(这也意味着将现有元素移动到新分配的内存空间)。如果您在开始时使用了reserve()
以确保已经有足够的分配内存,则当您使用push_back() 时,向量的
给它,但它不会再次分配新的内存,直到它用完您为其保留的空间。size()
将会增加resize()
not only allocates memory, it also creates as many instances as the desired size which you pass toresize()
as argument. Butreserve()
only allocates memory, it doesn't create instances. That is,Output (online demo):
So
resize()
may not be desirable, if you don't want the default-created objects. It will be slow as well. Besides, if youpush_back()
new elements to it, thesize()
of the vector will further increase by allocating new memory (which also means moving the existing elements to the newly allocated memory space). If you have usedreserve()
at the start to ensure there is already enough allocated memory, thesize()
of the vector will increase when youpush_back()
to it, but it will not allocate new memory again until it runs out of the space you reserved for it.从您的描述来看,您似乎想“保留”向量 t_Names 分配的存储空间。
请注意,
resize
初始化新分配的向量,其中reserve
仅分配但不构造。因此,“reserve”比“resize”快得多。您可以参考有关 调整大小 和保留
From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.
Take note that
resize
initialize the newly allocated vector wherereserve
just allocates but does not construct. Hence, 'reserve' is much faster than 'resize'You can refer to the documentation regarding the difference of resize and reserve
当您不希望对象在保留时被初始化时,则保留。此外,在调整大小时,您可能更愿意在逻辑上区分并跟踪其计数与使用计数。因此,界面中存在行为差异 - 保留时向量将表示相同数量的元素,并且在场景中调整大小时会大 100 个元素。
这完全取决于您与默认行为作斗争时的目标。有些人会喜欢定制分配器——但我们确实需要更好地了解您试图在程序中解决什么问题,以便为您提供良好的建议。
fwiw,许多向量实现在必须增长时只会将分配的元素数量加倍 - 您是否试图最小化峰值分配大小,或者是否试图为某些无锁程序或其他程序保留足够的空间?
reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.
it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.
fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?