This post will discuss how to concatenate multiple vectors in C++.

1. Using std::vector::insert

A simple solution to concatenate the contents of a vector into another vector is using the std::vector::insert member function. It can be used as follows:

Download  Run Code

Output:

1 2 3 4 5

 
To concatenate multiple vectors, we can overload the =operator and +=operator for vectors. For better performance, consider invoking the std::vector::reserve function before the std::vector::insert function. Following is a C++ implementation of the same:

Download  Run Code

Output:

1 2 3 4 5 6 7 8

2. Using Range v3 library

If permitted, use the ranges-v3 library to lazy concatenate contents of multiple vectors into a new vector. Here’s a one-liner using the ranges::view::concat function, which forms the basis for C++20’s std::ranges.

Download Code

Output:

1 2 3 4 5, 6, 7, 8

3. Using std::copy

Alternatively, we can use the std::copy standard algorithm to copy all elements from a given vector to another vector. This is demonstrated below using std::back_inserter, to allocate space for the new element.

Download  Run Code

Output:

1 2 3 4 5

4. Using std::move

Another plausible way to concatenate multiple vectors is using the std::move algorithm. Unlike the std::copy algorithm, std::move actually moves the objects rather than copying them. Its usage remains the same as the std::copy algorithm, as demonstrated below:

Download  Run Code

Output:

1 2 3 4 5

That’s all about concatenating multiple vectors in C++.