将向量附加到向量的最佳方法 [英] Best way to append vector to vector
问题描述
std::vector一种;std::vector乙;std::vectorC;
我想通过将 b
和 c
的元素附加到 a
来连接这三个向量.哪种方法最好,为什么?
1) 通过使用 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.清除();c.清除();
2) 通过使用 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.清除();c.清除();
3) 通过使用 std::move
(来自 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.清除();c.清除();
在我看来,你的第一个解决方案是最好的方法.
vector<>::insert
旨在添加元素,因此它是最合适的解决方案.
您可以在目标向量上调用 reserve
以保留一些空间,但除非您将大量向量加在一起,否则它可能不会提供太多好处:vector<>::insert
知道将添加多少元素,您将避免只调用一次 reserve
.
注意:如果那些是更复杂类型的vector
(即自定义类,甚至std::string
),那么使用std::move
可以为您提供很好的性能提升,因为它可以避免复制构造函数.然而,对于 int
的向量,它不会给你任何好处.
注意 2:值得一提的是,使用 std::move
会导致源 vector
的内容无法使用.>
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屋!