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


当前回答

vector1.insert( vector1.end(), vector2.begin(), vector2.end() );

其他回答

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

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

或者你可以用:

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

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

vector1.insert( vector1.end(), vector2.begin(), vector2.end() );

你可以为+操作符准备自己的模板:

template <typename T> 
inline T operator+(const T & a, const T & b)
{
    T res = a;
    res.insert(res.end(), b.begin(), b.end());
    return res;
}

接下来,使用+:

vector<int> a{1, 2, 3, 4};
vector<int> b{5, 6, 7, 8};
for (auto x: a + b)
    cout << x << " ";
cout << endl;

这个例子给出了输出:

1 2 3 4 5 6 7 8

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

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