OneBite.Dev - Coding blog in a bite size

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.

  1. We start by including the necessary library files i.e., <iostream> and <algorithm>.

  2. Next, we define a areEqual function that will take four parameters: the first array (arr1), the second array (arr2), and the sizes (n and m) for the given arrays.

  3. Inside this function, we first check if the lengths of two arrays are the same. If n is not equal to m then our function returns false, meaning the arrays are not equal.

  4. If the sizes are the same, we proceed by sorting both arrays.

  5. Then using a for loop, we compare each element of both arrays. If for some index i, arr1[i] is not equal to arr2[i], our function returns false meaning the arrays are not equal.

  6. If no inequality is found while comparing all the elements, function returns true, indicating that the arrays are equal.

  7. In the main function, we create two arrays and use the sizeof method to calculate the size of these arrays.

  8. 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.

c-plus-plus