Check If Two Arrays Are Equal In C++
Code snippet for how to Check If Two Arrays Are Equal In C++ with sample and detail explanation
When writing programs in C++, developers often face the task of comparing two arrays to find out if they are equal or not. This article will demonstrate how to check if two arrays are equal in C++ by illustrating a step-by-step tutorial with a simple code snippet.
Code snippet for Checking Array Equality
Here is the simple code snippet to check if two arrays are equal.
#include <iostream>
#include <algorithm>
bool areEqual(int arr1[], int arr2[], int n, int m)
{
if (n != m)
return false;
std::sort(arr1, arr1 + n);
std::sort(arr2, arr2 + m);
for (int i = 0; i < n; i++)
if (arr1[i] != arr2[i])
return false;
return true;
}
int main()
{
int arr1[] = {3, 5, 2, 5, 2};
int arr2[] = {2, 3, 5, 5, 2};
int n = sizeof(arr1) / sizeof(int);
int m = sizeof(arr2) / sizeof(int);
if (areEqual(arr1, arr2, n, m))
std::cout << "Yes";
else
std::cout << "No";
return 0;
}
Code Explanation for Checking Array Equality
The above code is a simple approach for comparing two arrays in C++ to check if they are equal or not.
-
We start by including the necessary library files i.e.,
<iostream>
and<algorithm>
. -
Next, we define a
areEqual
function that will take four parameters: the first array (arr1
), the second array (arr2
), and the sizes (n
andm
) for the given arrays. -
Inside this function, we first check if the lengths of two arrays are the same. If
n
is not equal tom
then our function returnsfalse
, meaning the arrays are not equal. -
If the sizes are the same, we proceed by sorting both arrays.
-
Then using a
for
loop, we compare each element of both arrays. If for some indexi
,arr1[i]
is not equal toarr2[i]
, our function returnsfalse
meaning the arrays are not equal. -
If no inequality is found while comparing all the elements, function returns
true
, indicating that the arrays are equal. -
In the
main
function, we create two arrays and use thesizeof
method to calculate the size of these arrays. -
Finally, we make a call to
areEqual
function with these arrays and sizes as arguments and print “Yes” if the arrays are identical, otherwise “No”.
This is a simple and effective way to check array equality in C++. The power of this approach lies in its simplicity, making it easy to understand and implement.