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:
- We start by including the necessary libraries. In this case,
iostream
,vector
andalgorithm
. - We then create a function
findUnion
that takes two arrays and their sizes as arguments. - Inside this function, we declare a vector
v
, which will be used to hold the union of the two arrays. - We use the
sort
command from thealgorithm
library to sort both arrays in ascending order. This helps us create a sorted union of the two arrays. - We declare two indices
i
andj
and initialize them to zero. These are used to iterate througharr1
andarr2
respectively. - A
while
loop is then used to compare the elements of the two arrays.- If an element in
arr1
is less than an element inarr2
, it is pushed to the vectorv
and the indexi
is incremented. - If an element in
arr2
is less, it is pushed tov
andj
is incremented. - If both elements are equal, one of them is pushed to
v
and bothi
andj
are incremented.
- If an element in
- Another couple of
while
loops are used to push the remaining elements in either of the arrays to the vectorv
. - The function finally returns the vector
v
. - In the
main
function, two arrays are declared and their union is found using our defined functionfindUnion
. - 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++.