追加矢量矢量的最佳方法 [英] Best way to append vector to vector

查看:190
本文介绍了追加矢量矢量的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的std ::矢量<&INT GT;一个;
的std ::矢量<&INT GT; b:
的std ::矢量<&INT GT; C;

我想通过附加的和 C B 取值元素<$来连接这三个矢量C $ C> A 。这是做到这一点的最好办法,为什么?


1)使用向量::插入

  a.reserve(a.size()+ b.size()+ c.size());
a.insert(a.end(),b.begin(),b.end());
a.insert(a.end(),c.begin(),c.end());
b.clear();
c.clear();

2)使用的std ::复制

  a.reserve(a.size()+ b.size()+ c.size());
性病::复制(b.begin(),b.end()的std ::插入(A,a.end()));
性病::复制(c.begin(),c.end()的std ::插入(A,a.end()));
b.clear();
c.clear();

3)使用的std ::移动(从 C ++ 11 ):

  a.reserve(a.size()+ b.size()+ c.size());
的std ::移动(b.begin(),b.end()的std ::插入(A,a.end()));
的std ::移动(c.begin(),c.end()的std ::插入(A,a.end()));
b.clear();
c.clear();


解决方案

在我看来,你的第一个解决方案是最好的一段路要走。

矢量&lt;方式&gt; ::插入的设计元素添加,因此是最合适的解决方案。

您可以致电储备的目的载体预留一些空间,但除非你增添了不少载体在一起,很可能是它不会提供太多的好处:矢量&lt;&GT; ::插入知道有多少元素将被添加,你会避免只有一个储备呼叫

注意的:如果这些均矢量更复杂的类型(即自定义类,甚至是的std ::字符串),然后使用的std ::移动可以为你提供一个不错的性能提升,因为这将避免拷贝构造函数。对于一个vector INT 但是,它不会给你带来任何好处。

注2 的:这是值得一提的是,使用的std ::移动将导致您的源矢量的内容为不可使用。

std::vector<int> a;
std::vector<int> b;
std::vector<int> c;

I would like to concatenate these three vectors by appending b's and c's elements to a. Which is the best way to do this, and why?


1) By using vector::insert:

a.reserve(a.size() + b.size() + c.size());
a.insert(a.end(), b.begin(), b.end());
a.insert(a.end(), c.begin(), c.end());
b.clear();
c.clear();

2) By using std::copy:

a.reserve(a.size() + b.size() + c.size());
std::copy(b.begin(), b.end(), std::inserter(a, a.end()));
std::copy(c.begin(), c.end(), std::inserter(a, a.end()));
b.clear();
c.clear();

3) By using std::move (from C++11):

a.reserve(a.size() + b.size() + c.size());
std::move(b.begin(), b.end(), std::inserter(a, a.end()));
std::move(c.begin(), c.end(), std::inserter(a, a.end()));
b.clear();
c.clear();

解决方案

In my opinion, your first solution is the best way to go.

vector<>::insert is designed to add element so it's the most adequate solution.

You could call reserve on the destination vector to reserve some space, but unless you add a lot of vector together, it's likely that it wont provide much benefits: vector<>::insert know how many elements will be added, you will avoid only one reserve call.

Note: If those were vector of more complex type (ie a custom class, or even std::string), then using std::move could provide you with a nice performance boost, because it would avoid the copy-constructor. For a vector of int however, it won't give you any benefits.

Note 2: It's worth mentioning that using std::move will cause your source vector's content to be unusable.

这篇关于追加矢量矢量的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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