OneBite.Dev - Coding blog in a bite size

Merge Multiple Array In C++

Code snippet for how to Merge Multiple Array In C++ with sample and detail explanation

Merging multiple arrays in C++ can be quite straightforward when the right steps are followed. This article will provide a simple guiding tutorial to help new and old programmers successfully carry out this operation.

Code Snippet: Merging Multiple Arrays

Let’s consider we have three arrays, namely, array1[] = {1,2,3}, array2[] = {4,5,6}, and array3[] = {7,8,9}. In C++, this is how you merge these arrays into a single array:

#include <iostream>
int main() 
{
    int array1[] = {1,2,3}, array2[] = {4,5,6}, array3[] = {7,8,9};
    int n1 = sizeof(array1) / sizeof(array1[0]); 
    int n2 = sizeof(array2) / sizeof(array2[0]); 
    int n3 = sizeof(array3) / sizeof(array3[0]); 
    int newArray[n1+n2+n3];
    int pos=0;

    for(int i=0; i<n1; i++)
        newArray[pos++] = array1[i]; 

    for(int i=0;i<n2; i++)
        newArray[pos++] = array2[i]; 

    for(int i=0; i<n3; i++)
        newArray[pos++] = array3[i]; 

    std::cout << "The merged array is: ";
    for (int i=0; i<(n1+n2+n3); i++)
        std::cout << newArray[i] << " "; 
    return 0;
}

When you run this code, the output will be: 1 2 3 4 5 6 7 8 9.

Code Explanation: Merging Multiple Arrays

The process of merging multiple arrays in C++ involves a few steps. Here they are, step-by-step:

  1. First, you declare the arrays that you want to merge. For instance, array1[] = {1,2,3}, array2[] = {4,5,6}, and array3[] = {7,8,9}.

  2. Then, we calculate the size of each of the arrays using sizeof(array)/sizeof(array[0]) which gives us the number of elements in each array.

  3. We then declare a new array newArray[], which will store the merged arrays. The size of this new array is the sum of the sizes of the arrays that we want to merge.

  4. Now, for the merging operation. We do this by using a for loop to copy each element from the old arrays to the new one. We use the variable pos to keep track of the position in the new array where the next element will be copied.

  5. We then proceed to print our new array using another for loop.

This way you can easily merge multiple arrays in C++. The code outlined in this tutorial is quite basic. Depending on your use case, you may need to sort the arrays first, or handle other edge cases or conditions. This tutorial, however, provides a starting point to merging arrays in C++.

c-plus-plus