我如何连接两个std::向量?
当前回答
如果希望能够简洁地连接向量,可以重载+=运算符。
template <typename T>
std::vector<T>& operator +=(std::vector<T>& vector1, const std::vector<T>& vector2) {
vector1.insert(vector1.end(), vector2.begin(), vector2.end());
return vector1;
}
然后你可以这样调用它:
vector1 += vector2;
其他回答
或者你可以用:
std::copy(source.begin(), source.end(), std::back_inserter(destination));
如果两个向量不包含完全相同类型的内容,则此模式非常有用,因为您可以使用某些内容而不是std::back_inserter来从一种类型转换为另一种类型。
std::vector<int> first;
std::vector<int> second;
first.insert(first.end(), second.begin(), second.end());
vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
如果你对强异常保证感兴趣(当复制构造函数可以抛出异常时):
template<typename T>
inline void append_copy(std::vector<T>& v1, const std::vector<T>& v2)
{
const auto orig_v1_size = v1.size();
v1.reserve(orig_v1_size + v2.size());
try
{
v1.insert(v1.end(), v2.begin(), v2.end());
}
catch(...)
{
v1.erase(v1.begin() + orig_v1_size, v1.end());
throw;
}
}
如果vector元素的move构造函数可以抛出(这是不太可能的,但仍然是),那么具有强保证的类似append_move通常不能实现。
你可以为+操作符准备自己的模板:
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