OneBite.Dev - Coding blog in a bite size

Find The Union Of Two Arrays In C++

Code snippet for how to Find The Union Of Two Arrays In C++ with sample and detail explanation

Finding the union of two arrays in C++ is a common task in programming. This short article will guide you on how you can easily accomplish this task via a straightforward tutorial.

Code snippet: Finding the Union of Two Arrays

Below is a simple code in C++ that demonstrates how to find the union of two arrays:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

vector<int> findUnion(int arr1[], int arr2[], int n, int m)
{
    vector<int> v;

    sort(arr1, arr1 + n);
    sort(arr2, arr2 + m);

    int i = 0, j = 0;
    while(i < n && j < m)
    {
        if(arr1[i] < arr2[j])
            v.push_back(arr1[i++]);

        else if(arr2[j] < arr1[i])
            v.push_back(arr2[j++]);

        else
        {
            v.push_back(arr2[j++]);
            i++;
        }
    }

    while(i < n)
        v.push_back(arr1[i++]);

    while(j < m)
        v.push_back(arr2[j++]);

    return v;
}

int main()
{
    int arr1[] = {1, 2, 5, 6, 8};
    int arr2[] = {1, 3, 4, 6, 7};

    vector<int> vec = findUnion(arr1, arr2, 5, 5);

    for(auto x : vec)
        cout << x << " ";

    return 0;
}

Code Explanation: Finding the Union of Two Arrays

In this tutorial, we’re attempting to find the union of two arrays. Here is a step by step insight on what the code does:

  1. We start by including the necessary libraries. In this case, iostream, vector and algorithm.
  2. We then create a function findUnion that takes two arrays and their sizes as arguments.
  3. Inside this function, we declare a vector v, which will be used to hold the union of the two arrays.
  4. We use the sort command from the algorithm library to sort both arrays in ascending order. This helps us create a sorted union of the two arrays.
  5. We declare two indices i and j and initialize them to zero. These are used to iterate through arr1 and arr2 respectively.
  6. A while loop is then used to compare the elements of the two arrays.
    • If an element in arr1 is less than an element in arr2, it is pushed to the vector v and the index i is incremented.
    • If an element in arr2 is less, it is pushed to v and j is incremented.
    • If both elements are equal, one of them is pushed to v and both i and j are incremented.
  7. Another couple of while loops are used to push the remaining elements in either of the arrays to the vector v.
  8. The function finally returns the vector v.
  9. In the main function, two arrays are declared and their union is found using our defined function findUnion.
  10. The union is then printed to the console using a range-based for loop.

To recap, this tutorial has shown you a simple and effective method to find the union of two arrays in C++.

c-plus-plus