使用初始值(重新)将向量初始化为一定长度

发布于 2024-07-06 13:13:24 字数 320 浏览 5 评论 0原文

作为函数参数,我得到一个 vector& vec(输出向量,因此非常量),长度和值未知。 我想将此向量初始化为全零的特定长度 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

匿名的好友 2024-07-13 13:13:24
std::vector<double>(n).swap(vec);

此后,保证 vec 的大小和容量为 n,所有值均为 0.0。

也许自 C++11 以来更惯用的方法是

vec.assign(n, 0.);
vec.shrink_to_fit();

第二行可选。 在 vec 开始时包含超过 n 个元素的情况下,是否调用 shr​​ink_to_fit 是保留比实际更多内存之间的权衡需要与执行重新分配。

std::vector<double>(n).swap(vec);

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

vec.assign(n, 0.);
vec.shrink_to_fit();

with the second line optional. In the case where vec starts off with more than n elements, whether to call shrink_to_fit is a trade-off between holding onto more memory than is required vs performing a re-allocation.

若言繁花未落 2024-07-13 13:13:24
std::vector<double>(n).swap(vec);

这也具有实际压缩向量的优点。 (在第一个示例中, clear() 不保证压缩向量。)

std::vector<double>(n).swap(vec);

This has the advantage of actually compacting your vector too. (In your first example, clear() does not guarantee to compact your vector.)

鸵鸟症 2024-07-13 13:13:24

好吧,让我们完善一下执行此操作的方法:)

vec.swap(std::vector<double>(n));
std::vector<double>(n).swap(vec);
std::swap(vector<double>(n), vec);
std::swap(vec, vector<double>(n));

Well let's round out the ways to do this :)

vec.swap(std::vector<double>(n));
std::vector<double>(n).swap(vec);
std::swap(vector<double>(n), vec);
std::swap(vec, vector<double>(n));
送舟行 2024-07-13 13:13:24

您发布的代码片段都没有进行任何内存释放,因此它们大致相等。

其他人不断发布的交换技巧将需要更长的时间来执行,因为它将释放向量最初使用的内存。 这可能是所希望的,也可能不是所希望的。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文