我如何连接两个std::向量?


当前回答

对于range v3,你可能会有一个惰性连接:

ranges::view::concat(v1, v2)

演示。

其他回答

或者你可以用:

std::copy(source.begin(), source.end(), std::back_inserter(destination));

如果两个向量不包含完全相同类型的内容,则此模式非常有用,因为您可以使用某些内容而不是std::back_inserter来从一种类型转换为另一种类型。

在c++ 11中,我更喜欢将向量b附加到a:

std::move(b.begin(), b.end(), std::back_inserter(a));

当a和b不重叠时,b不会再被用到。


这是std::move from <algorithm>,而不是通常的std::move from <utility>。

std::vector<int> first;
std::vector<int> second;

first.insert(first.end(), second.begin(), second.end());

对于提供push_back (string, vector, deque,…)功能的容器:

Std::copy(Std::begin(input), Std::end(input), Std::back_inserter(output))

and

对于提供insert (map, sets)功能的容器:

Std::copy(Std::begin(input), Std::end(input), Std::inserter(output, output.end()))

连接的一般性能提升是检查向量的大小。然后将较小的一个与较大的一个合并/插入。

//vector<int> v1,v2;
if(v1.size()>v2.size()) {
    v1.insert(v1.end(),v2.begin(),v2.end());
} else {
    v2.insert(v2.end(),v1.begin(),v1.end());
}