连接两个std :: vector-哪个方法更有效以及如何/为什么? [英] Concatenating two std::vector -- which method is more efficient and how/why?

查看:97
本文介绍了连接两个std :: vector-哪个方法更有效以及如何/为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下情形:

std::vector<int> A;
std::vector<int> B;
std::vector<int> AB;

我希望 AB 包含 A ,然后按相同顺序依次显示 B 的内容。

I want AB to have contents of A and then the contents of B in the same order.

方法1:

AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );

方法2:

std::vector<int> AB ( A.begin(), A.end() ); // calling constructor
AB.insert ( AB.end(), B.begin(), B.end() );

以上哪种方法更有效?为什么?
还有另一种更有效的方法吗?

Which one of the above methods is more efficient? Why? Is there a different method that is more efficient?

推荐答案

我认为第一个方法总是比第一个方法快。第二个因为它只会执行一次内存分配,而第二个可能将不得不至少重新分配一次。但是我的尺寸似乎表明,对于小于100,000的尺寸,这甚至更快:

I think the first one will always be faster than the second one because it will only perform one memory allocation and the second one will probably have to reallocate at least once. But my measurements seem to indicate that for sizes less than about 100,000 this is even faster:

std::vector<int> AB(A.size() + B.size());
std::copy(A.begin(), A.end(), AB.begin());
std::copy(B.begin(), B.end(), AB.begin() + B.size());

我猜这是因为,这不仅只执行一次分配,而且没有重新分配,甚至不需要检查是否应该进行任何重新分配。缺点是可能最初必须将所有内存清零,但我认为CPU擅长于此。

I'm guessing this is because, not only does this only perform one allocation and no reallocation, it doesn't even need to check if it should do any reallocation. The downside is it may have to zero out all the memory initially, but I think CPUs are good at that.

这篇关于连接两个std :: vector-哪个方法更有效以及如何/为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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