Concatenating two std::vectors

2018-12-31 23:14发布

How do I concatenate two std::vectors?

18条回答
孤独寂梦人
2楼-- · 2018-12-31 23:46

Or you could use:

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

This pattern is useful if the two vectors don't contain exactly the same type of thing, because you can use something instead of std::back_inserter to convert from one type to the other.

查看更多
君临天下
3楼-- · 2018-12-31 23:48
std::vector<int> first;
std::vector<int> second;

first.insert(first.end(), second.begin(), second.end());
查看更多
梦寄多情
4楼-- · 2018-12-31 23:49

Here's a general purpose solution using C++11 move semantics:

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);
}

Note how this differs from appending to a vector.

查看更多
听够珍惜
5楼-- · 2018-12-31 23:50

With range v3, you may have a lazy concatenation:

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

Demo.

查看更多
何处买醉
6楼-- · 2018-12-31 23:51

A general performance boost for concatenate is to check the size of the vectors. And merge/insert the smaller one with the larger one.

//vector<int> v1,v2;
if(v1.size()>v2.size()){
    v1.insert(v1.end(),v2.begin(),v2.end());
}else{
    v1.insert(v2.end(),v1.begin(),v1.end());
}
查看更多
看风景的人
7楼-- · 2018-12-31 23:54

With C++11, I'd prefer following to append vector b to a:

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

when a and b are not overlapped, and b is not going to be used anymore.


This is std::move from <algorithm>, not the usual std::move from <utility>.

查看更多
登录 后发表回答