Join two arrays in C++
This post will discuss how to join two arrays into a new array in C++. The new array should contain elements of the first array, followed by elements of the second array in the same order.
1. Write our own routine
A naive solution is to create a new array of size enough to accommodate all elements of both arrays and fill it with all elements of the first array, followed by all elements of the second array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include <iostream> #include <algorithm> int main() { int X[] = { 1, 2, 3 }; int Y[] = { 4, 5, 6 }; int m = sizeof(X)/sizeof(X[0]); int n = sizeof(Y)/sizeof(Y[0]); int arr[m + n]; for (int i = 0; i < m + n; i++) { if (i < m) { arr[i] = X[i]; } else { arr[i] = Y[i - m]; } } for (int i = 0; i < m + n; i++) { std::cout << arr[i] << ' '; } return 0; } |
Output:
1 2 3 4 5 6
2. Using std::copy function
The recommended approach is to use the std::copy from <algorithm> header, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <algorithm> int main() { int X[] = { 1, 2, 3 }; int Y[] = { 4, 5, 6 }; int m = sizeof(X)/sizeof(X[0]); int n = sizeof(Y)/sizeof(Y[0]); int arr[m + n]; std::copy(X, X + m, arr); std::copy(Y, Y + n, arr + m); // or, use // std::copy(Y, Y + n, std::copy(X, X + m, arr)); for (int i = 0; i < m + n; i++) { std::cout << arr[i] << ' '; } return 0; } |
Output:
1 2 3 4 5 6
That’s all about joining two arrays 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 :)