我如何连接两个std::向量?
当前回答
将这个添加到头文件中:
template <typename T> vector<T> concat(vector<T> &a, vector<T> &b) {
vector<T> ret = vector<T>();
copy(a.begin(), a.end(), back_inserter(ret));
copy(b.begin(), b.end(), back_inserter(ret));
return ret;
}
然后这样用:
vector<int> a = vector<int>();
vector<int> b = vector<int>();
a.push_back(1);
a.push_back(2);
b.push_back(62);
vector<int> r = concat(a, b);
R将包含[1,2,62]
其他回答
我将使用插入函数,类似于:
vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.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());
}
或者你可以用:
std::copy(source.begin(), source.end(), std::back_inserter(destination));
如果两个向量不包含完全相同类型的内容,则此模式非常有用,因为您可以使用某些内容而不是std::back_inserter来从一种类型转换为另一种类型。
对于range v3,你可能会有一个惰性连接:
ranges::view::concat(v1, v2)
演示。
下面是一个使用c++ 11移动语义的通用解决方案:
template <typename T>
std::vector<T> concat(const std::vector<T>& lhs, const std::vector<T>& rhs)
{
if (lhs.empty()) return rhs;
if (rhs.empty()) return lhs;
std::vector<T> result {};
result.reserve(lhs.size() + rhs.size());
result.insert(result.cend(), lhs.cbegin(), lhs.cend());
result.insert(result.cend(), rhs.cbegin(), rhs.cend());
return result;
}
template <typename T>
std::vector<T> concat(std::vector<T>&& lhs, const std::vector<T>& rhs)
{
lhs.insert(lhs.cend(), rhs.cbegin(), rhs.cend());
return std::move(lhs);
}
template <typename T>
std::vector<T> concat(const std::vector<T>& lhs, std::vector<T>&& rhs)
{
rhs.insert(rhs.cbegin(), lhs.cbegin(), lhs.cend());
return std::move(rhs);
}
template <typename T>
std::vector<T> concat(std::vector<T>&& lhs, std::vector<T>&& rhs)
{
if (lhs.empty()) return std::move(rhs);
lhs.insert(lhs.cend(), std::make_move_iterator(rhs.begin()), std::make_move_iterator(rhs.end()));
return std::move(lhs);
}
注意这与附加到向量有何不同。