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


当前回答

我将使用插入函数,类似于:

vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());

其他回答

或者你可以用:

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

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

我将使用插入函数,类似于:

vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());
vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {11, 12, 13, 14, 15};
copy(v2.begin(), v2.end(), back_inserter(v1));

对于提供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()))

我更喜欢前面提到的一个:

a.insert(a.end(), b.begin(), b.end());

但是如果你使用c++ 11,有一个更通用的方法:

a.insert(std::end(a), std::begin(b), std::end(b));

另外,这不是问题的一部分,但建议在追加之前使用reserve以获得更好的性能。如果你把向量和它自己连接起来,如果不保留,它就失败了,所以你总是应该保留。


所以基本上你需要:

template <typename T>
void Append(std::vector<T>& a, const std::vector<T>& b)
{
    a.reserve(a.size() + b.size());
    a.insert(a.end(), b.begin(), b.end());
}