Open In App

How to Compare Arrays in C++?

Last Updated : 09 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, arrays are linear data structures that can store data of the same type in contiguous memory locations. In this article, we will learn how to compare two arrays to check whether they are equal or not in C++.

Example:

Input:
arr1[] = {1, 2, 4, 3, 5, 11}
arr2[] = {1 2, 3, 4 ,5}

Output:
arr1 and arr2 are not equal

Compare Arrays in C++

To compare two arrays in C++, we can use the std::equal method provided by the Standard Template Library(STL). This function will return true if all the corresponding values in two arrays are equal. If they are not equal, it returns false. Following is the syntax to use the std::equal method:

Syntax

equal(begin(arr1), end(arr1), begin(arr2))

where:

  • begin(arr1): returns an iterator pointing to the first element of the first array.
  • end(arr1): returns an iterator pointing to the end of the first array.
  • begin(arr2): returns an iterator pointing to the first element of the second array.

C++ Program to Compare Two Arrays

The following program demonstrates how we can compare two arrays in C++:

C++
// C++ Program to demonstrate how to compare two arrays
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
    // Initialize two arrays
    int arr1[] = { 1, 2, 4, 3, 5, 11 };
    int arr2[] = { 1, 2, 3, 4, 5 };

    // Compare both the arrays
    bool isEqual
        = equal(begin(arr1), end(arr1), begin(arr2));

    if (isEqual) {
        cout << "Arrays are equal." << endl;
    }
    else {
        cout << "Arrays are not equal." << endl;
    }

    return 0;
}

Output
Arrays are not equal.

Time Complexity: O(N), where N denotes the size of the arrays.
Auxiliary Space: O(1)


Next Article
Practice Tags :

Similar Reads