C++ vector::resize() 和 vector::reserve() 之间的选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7397768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:52:25  来源:igfitidea点击:

Choice between vector::resize() and vector::reserve()

c++vector

提问by iammilind

I am pre-allocating some memory to my a vectormember variable. Below code is minimal part

我正在为我的vector成员变量预先分配一些内存。下面的代码是最小的部分

class A {
  vector<string> t_Names;
public:
  A () : t_Names(1000) {}
};

Now at some point of time, if the t_Names.size()equals 1000. I am intending to increase the size by 100. Then if it reaches 1100, again increase by 100and so on.

现在在某个时间点,如果t_Names.size()等于1000. 我打算将大小增加100. 然后如果达到1100,再增加100,依此类推。

My question is, what to choose between vector::resize()and vector::reserve(). Is there any better choice in this kind of scenario ?

我的问题是,在vector::resize()和之间选择什么vector::reserve()。在这种情况下还有更好的选择吗?

Edit: I have sort of precise estimate for the t_Names. I estimate it to be around 700to 800. However in certain(seldom) situations, it can grow more than 1000.

编辑:我对t_Names. 我估计大约700800. 但是在某些(很少)情况下,它可以增长超过1000.

回答by Jan Hudec

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 the size(), iteration will go over all those elements, push_back will insert after them and you can directly access them using the operator[].

resize()方法(并将参数传递给构造函数等效于该方法)将向向量插入或删除适当数量的元素以使其给定大小(它具有可选的第二个参数来指定它们的值)。它会影响size(),迭代将遍历所有这些元素,push_back 将在它们之后插入,您可以使用operator[].

The reserve()method only allocates memory, but leaves it uninitialized. It only affects capacity(), but size()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.

reserve()方法只分配内存,但未初始化。它只影响capacity(),但size()不会改变。对象没有价值,因为没有向向量添加任何内容。如果然后插入元素,则不会发生重新分配,因为它是提前完成的,但这是唯一的效果。

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, use reserve().

所以这取决于你想要什么。如果您想要包含 1000 个默认项的数组,请使用resize(). 如果您想要一个数组,您希望在其中插入 1000 个项目并希望避免多次分配,请使用reserve().

EDIT:Blastfurnace's comment made me read the question again and realize, that in your case the correct answer is don't preallocatemanually. Just keep inserting the elements at the end as you need. The vector will automatically reallocate as needed and will do it moreefficiently 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.

编辑:Blastfurnace 的评论让我再次阅读了这个问题并意识到,在你的情况下,正确的答案是不要手动预分配。只需根据需要在最后插入元素即可。矢量将根据需要自动重新分配,并且比提到的手动方式有效。唯一reserve()有意义的情况是当您对需要的总大小进行合理精确的估计时,可以轻松获得。

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.

EDIT2:广告问题编辑:如果您有初步估计,则reserve()该估计。如果结果还不够,就让向量来做它的事情。

回答by Nawaz

resize()not only allocates memory, it also createsas many instances as the desiredsize which you pass to resize()as argument. But reserve()only allocates memory, it doesn't create instances. That is,

resize()不仅分配内存,它还创建与您作为参数传递的所需大小一样多的实例resize()。但reserve()只分配内存,不创建实例。那是,

std::vector<int> v1;
v1.resize(1000); //allocation + instance creation
cout <<(v1.size() == 1000)<< endl;   //prints 1
cout <<(v1.capacity()==1000)<< endl; //prints 1

std::vector<int> v2;
v2.reserve(1000); //only allocation
cout <<(v2.size() == 1000)<< endl;   //prints 0
cout <<(v2.capacity()==1000)<< endl; //prints 1

Output (online demo):

输出(在线演示):

1
1
0
1

So resize()may not be desirable, if you don't want the default-created objects. It will be slow as well. Besides, if you push_back()new elements to it, the size()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 used reserve()at the start to ensure there is already enough allocated memory, the size()of the vector will increase when you push_back()to it, but it will not allocate new memory again until it runs out of the space you reserved for it.

因此resize(),如果您不想要默认创建的对象,则可能不是可取的。它也会很慢。此外,如果push_back()向它添加新元素,size()向量的 将通过分配新内存进一步增加(这也意味着将现有元素移动到新分配的内存空间)。如果您reserve()在开始时使用以确保已经有足够的分配内存,那么size()当您push_back()使用它时,vector 的值会增加,但它不会再次分配新内存,直到它用完您为其保留的空间

回答by dip

From your description, it looks like that you want to "reserve" the allocated storage space of vector t_Names.

从您的描述来看,您似乎想“保留”向量t_Names 的分配存储空间。

Take note that resizeinitialize the newly allocated vector where reservejust allocates but does not construct. Hence, 'reserve' is much fasterthan 'resize'

请注意,resizereserve仅分配但不构造的地方初始化新分配的向量。因此,“reserve”比“resize”快得多

You can refer to the documentation regarding the difference of resizeand reserve

resizereserve的区别可以参考文档

回答by justin

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.

当您不希望在保留时初始化对象时保留。此外,您可能更喜欢在调整大小时在逻辑上区分和跟踪其计数与使用计数。所以界面中存在行为差异 - 保留时向量将表示相同数量的元素,并且在您的场景中调整大小时将大 100 个元素。

Is there any better choice in this kind of 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?

fwiw,许多向量实现在它们必须增长时只会将分配的元素数量加倍 - 您是在尝试最小化峰值分配大小还是在尝试为某些无锁程序或其他东西保留足够的空间?