Construction a vector from the concatenation of 2 vectors

后端 未结 6 436
梦谈多话
梦谈多话 2021-01-12 22:45

Is there a way to construct a vector as the concatenation of 2 vectors (Other than creating a helper function?)

For example:



        
6条回答
  •  鱼传尺愫
    2021-01-12 23:23

    I think you have to write a help function. I'd write it as:

    std::vector concatenate(const std::vector& lhs, const std::vector& rhs)
    {
        auto result = lhs;
        std::copy( rhs.begin(), rhs.end(), std::back_inserter(result) );
        return result;
    }
    

    The call it as:

        const auto concatenation = concatenate(first, second);
    

    If the vectors are likely to be very large (or contain elements that are expensive to copy), then you might need to do a reserve first to save reallocations:

    std::vector concatenate(const std::vector& lhs, const std::vector& rhs)
    {
        std::vector result;
        result.reserve( lhs.size() + rhs.size() );
        std::copy( lhs.begin(), lhs.end(), std::back_inserter(result) );
        std::copy( rhs.begin(), rhs.end(), std::back_inserter(result) );
        return result;
    }
    

    (Personally, I would only bother if there was evidence it was a bottleneck).

提交回复
热议问题