什么是最有效的方式追加一个std :: vector到另一个结束? [英] What is the most efficient way to append one std::vector to the end of another?

查看:249
本文介绍了什么是最有效的方式追加一个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到另一个结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆