OneBite.Dev - Coding blog in a bite size

Find The Unique Elements In Two Arrays In C++

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

In C++, dealing with arrays is quite common, and at times, you may need to find the unique elements in two separate arrays. In this article, we are going to illustrate how to find the unique elements in two arrays.

Code Snippet: Finding Unique Elements in Two Arrays in C++

#include<iostream>
#include<unordered_set>
using namespace std;

void findUniqueElements(int arr1[], int arr2[], int n, int m)
{
    unordered_set<int> set1(arr1, arr1 + n);
    for (int i = 0; i < m; i++)
    {
        if (set1.find(arr2[i]) == set1.end())
        {
            cout << arr2[i] << " ";
        }
    }
}

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

    findUniqueElements(arr1, arr2, n, m);

    return 0;
}

Code Explanation: Finding Unique Elements in Two Arrays in C++

Initially, we include the necessary libraries for printing to the console (iostream) and using an unordered set (unordered_set).

Next, we declare and define the findUniqueElements function. This function takes four arguments:

  • two integer arrays (arr1 and arr2),
  • and their respective sizes (n and m).

Inside the function, we create an unordered set (set1) from the elements of the first array (arr1). Then, we iterate over the second array (arr2). For every element in arr2, we check if it exists in set1. If it doesn’t exist—which we determine if set1.find(arr2[i]) equals set1.end()—we print the element to the console. This process helps us find the unique elements in the two arrays.

Finally, inside the main function, we declare and initialize both arrays and their sizes. We then call findUniqueElements to find the unique elements and print them.

Run the program, and you’ll see that it prints 6 7 8 , which are the unique elements in the arr2 as compared to arr1.

This method allows swift array traversal, even for large data sets, and does not involve any complex calculations or algorithms.

c-plus-plus