This post will discuss how to create a copy of an array in C++.

1. Using std::copy

The recommended solution for copying all elements from an array to another array is using the standard algorithm std::copy from the <algorithm> header. The following code example shows invocation for this function:

Download  Run Code

Output:

1, 3, 5, 7, 9

 
We can also use the std::n_copy algorithm from the <algorithm> header, as demonstrated below:

Download  Run Code

Output:

1, 3, 5, 7, 9

2. Using copy constructor

Since C++11, we can directly copy std::array with the assignment operator or the copy constructor. This doesn’t work for C-style arrays.

Download  Run Code

Output:

1, 3, 5, 7, 9

3. Using for loop

Another solution is to loop through the source array using an index-based for-loop and add each encountered element to its correct position in the destination array. This would translate to a simple code below:

Download  Run Code

Output:

1, 3, 5, 7, 9

4. Using std::memcpy

For arrays of POD (Plain Old Data) type like int, char, etc., we can perform a binary copy of the array using the std::memcpy function. Here’s what the code would look like.

Download  Run Code

Output:

1, 3, 5, 7, 9

That’s all about creating a copy of an array in C++.