This post will discuss how to concatenate two arrays together in C++.

1. Using std::copy

The recommended solution is to use the std::copy from the <algorithm> header to concatenate two arrays. The idea is to allocate memory large enough to store all values of both arrays, then copy the values into the new array with std::copy.

Download  Run Code

Output:

1 2 3 4 5

 
The std::copy function returns an iterator to the range’s end where elements have been copied. Therefore, the code can be shortened to:

Download  Run Code

Output:

1 2 3 4 5

 
Alternately, we can use the std::copy_n standard algorithm, which copies the first n elements of the specified range to the result.

Download  Run Code

Output:

1 2 3 4 5

2. Using std::memcpy

The std::memcpy performs a binary copy of the arrays of POD (Plain Old Data) type like int, char, etc. We can use it to concatenate two arrays of POD types. It is declared in header <cstring>. This is demonstrated below:

Download  Run Code

Output:

1 2 3 4 5

3. Using Fold Expressions

With C++17, we can use fold expressions to concatenate a sequence of std::arrays. This elegant and efficient solution is demonstrated below:

Download  Run Code

Output:

1 2 3 4 5

That’s all about concatenating two arrays together in C++.