什么是最有效的方式追加一个std :: vector到另一个结束?

编程入门 行业动态 更新时间:2024-10-26 13:36:04
本文介绍了什么是最有效的方式追加一个std :: vector到另一个结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让v1成为目标向量,v2需要附加到它的后面。

Let v1 be the target vector, v2 needs to be appended to the back of it.

我现在在做:

v1.reserve(v1.size() + v2.size()); copy(v2.begin(), v2.end(), back_inserter(v1));

这是最有效的方法吗?或者可以通过复制一块内存来完成? 谢谢!

Is this the most efficient way? Or can it maybe be done just via copying a chunk of memory? Thanks!

推荐答案

经过很多争论(以及Matthieu M.和villintehaspam的合理评论)将改变我的建议到

After a lot of arguing (and a reasonable comment from Matthieu M. and villintehaspam), I'll change my suggestion to

v1.insert( v1.end(), v2.begin(), v2.end() );

我会保留前面的建议:

v1.reserve( v1.size() + v2.size() ); v1.insert( v1.end(), v2.begin(), v2.end() );

后面的方法有一些原因,虽然没有一个足够强:

There are some reasons to do it the latter way, although none of them enough strong:

  • 不能保证向量将被重新分配的大小 - 例如如果总和大小是1025,则可以将其重新分配给2048,这取决于实现。对于 reserve 没有这样的保证,但是对于一个特定的实现,它可能是真的。如果寻找瓶颈,可能是合理的检查。
  • 保留说明我们的意图明确 - 在这种情况下优化可能更有效(保留可以准备高速缓存在一些顶尖 reserve 我们有一个C ++标准保证,只有一个重新分配,而 insert 可能无法有效地执行,并做了几个重新分配(也是用特定实现测试的东西)。
  • there is no guarantee on to what size will the vector be reallocated -- e.g. if the sum size is 1025, it may get reallocated to 2048 -- dependant on implementation. There is no such guarantee for reserve either, but for a specific implementation it might be true. If hunting for a bottleneck it might be rasonable to check that.
  • reserve states our intentions clear -- optimization may be more efficient in this case (reserve could prepare the cache in some top-notch implementation).
  • also, with reserve we have a C++ Standard guarantee that there will be only a single reallocation, while insert might be implemented inefficiently and do several reallocations (also something to test with a particular implementation).

更多推荐

什么是最有效的方式追加一个std :: vector到另一个结束?

本文发布于:2023-11-29 18:19:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647217.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最有效   结束   方式   std   vector

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!