This post will discuss how to compare arrays for equality in C++.

1. Using == operator

We can easily compare two std::array using the == operator. It checks whether the contents of the two containers are equal or not. Consider the following code demonstrating this:

Download  Run Code

Output:

Both arrays are equal

 
Note that you can’t compare two C-style arrays using this approach, since it decays to pointers to the first elements of the respective arrays, and we will end up comparing two addresses. The following C++ program demonstrates it:

Download  Run Code

Output:

Both arrays are not equal

2. Using std::equal

Alternatively, we can use the std::equal function to determine if corresponding elements in the specified ranges are equal. The following example shows how to compare two arrays with the std::equal function.

Notice the length check before calling the std::equal function. This is done to avoid incorrect output when the second array contains more elements than in the first array.

Download  Run Code

Output:

Both arrays are equal

 
With C++11, we can pass an iterator to the beginning and end of the array to the std::equal function:

Download  Run Code

Output:

Both arrays are equal

3. Using Custom Logic

Another option is to write custom logic for comparing two arrays in C++. The idea is to iterate with indices and compare the corresponding elements at the respective position in both arrays. Here’s what the code would look like:

Download  Run Code

Output:

Both arrays are equal

4. Using memcmp() function

Finally, we can compare two blocks of memory using the memcmp() function. It returns 0 if the contents of both memory blocks are equal, as shown below:

Download  Run Code

Output:

Both arrays are not equal

That’s all about comparing arrays for equality in C++.