使用初始值(重新)将向量初始化为一定长度
作为函数参数,我得到一个 vector
(输出向量,因此非常量),长度和值未知。 我想将此向量初始化为全零的特定长度 n 。
这会起作用
vec.clear();
vec.resize( n, 0.0 );
这也会起作用:
vec.resize( n );
vec.assign( n, 0.0 );
第二个是否更有效(因为不涉及内存释放/分配)? 有没有更有效的方法来做到这一点?
As a function argument I get a vector<double>& vec
(an output vector, hence non-const) with unknown length and values. I want to initialise this vector to a specific length n with all zeroes.
This will work
vec.clear();
vec.resize( n, 0.0 );
And this will work as well:
vec.resize( n );
vec.assign( n, 0.0 );
Is the second more efficient (because no memory deallocation/allocation is involved)? Is there a more efficient way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
此后,保证 vec 的大小和容量为 n,所有值均为 0.0。
也许自 C++11 以来更惯用的方法是
第二行可选。 在
vec
开始时包含超过n
个元素的情况下,是否调用shrink_to_fit
是保留比实际更多内存之间的权衡需要与执行重新分配。After this, vec is guaranteed to have size and capacity n, with all values 0.0.
Perhaps the more idiomatic way since C++11 is
with the second line optional. In the case where
vec
starts off with more thann
elements, whether to callshrink_to_fit
is a trade-off between holding onto more memory than is required vs performing a re-allocation.这也具有实际压缩向量的优点。 (在第一个示例中,
clear()
不保证压缩向量。)This has the advantage of actually compacting your vector too. (In your first example,
clear()
does not guarantee to compact your vector.)好吧,让我们完善一下执行此操作的方法:)
Well let's round out the ways to do this :)
您发布的代码片段都没有进行任何内存释放,因此它们大致相等。
其他人不断发布的交换技巧将需要更长的时间来执行,因为它将释放向量最初使用的内存。 这可能是所希望的,也可能不是所希望的。
Neither of the code snippets that you posted do any memory deallocation, so they are roughly equal.
The swap trick that everyone else keeps posting will take longer to execute, because it will deallocate the memory originally used by the vector. This may or may not be desirable.