Create a copy of an array in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <algorithm> #include <iterator> int main() { const int n = 5; int src[] = {1, 3, 5, 7, 9}; int dest[n]; std::copy(std::begin(src), std::end(src), std::begin(dest)); for (int &i: dest) { std::cout << i << ' '; } return 0; } |
Output:
1, 3, 5, 7, 9
We can also use the std::n_copy algorithm from the <algorithm> header, as demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <algorithm> #include <iterator> int main() { const int n = 5; int src[] = {1, 3, 5, 7, 9}; int dest[n]; std::copy_n(src, n, dest); for (int &i: dest) { std::cout << i << ' '; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <array> int main() { const int n = 5; std::array<int, n> src = {1, 3, 5, 7, 9}; std::array<int, n> dest = src; // or, std::array<int, n> dest(src); for (int &i: dest) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> int main() { const int n = 5; int src[] = {1, 3, 5, 7, 9}; int dest[n]; for (int i = 0; i < n; i++) { dest[i] = src[i]; } for (int &i: dest) { std::cout << i << ' '; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <cstring> int main() { const int n = 5; int src[] = {1, 3, 5, 7, 9}; int dest[n]; std::memcpy(&dest, &src, sizeof(src)); for (int &i: dest) { std::cout << i << ' '; } return 0; } |
Output:
1, 3, 5, 7, 9
That’s all about creating a copy of an array in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)