Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing arrays for equality in C++

Can someone please explain to me why the output from the following code is saying that arrays are not equal?

int main() {      int iar1[] = {1,2,3,4,5};     int iar2[] = {1,2,3,4,5};      if (iar1 == iar2)         cout << "Arrays are equal.";     else         cout << "Arrays are not equal.";      return 0;    } 
like image 901
vladinkoc Avatar asked Oct 12 '12 20:10

vladinkoc


People also ask

How do you check the equality of two arrays in C?

Algorithm to check if two arrays are equal or notInput the number of elements of arr1 and arr2. Input the elements of arr1 and arr2. If all the elements of arr1 and arr2 are equal, then print "Same". Else, print "Not Same".

How do you compare two arrays are equal?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

Can you use == for arrays?

For arrays, the equals() method is the same as the == operator. So, planes1. equals(planes2) returns true because both references are referring to the same object.

Can we directly compare two array?

Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).


1 Answers

if (iar1 == iar2) 

Here iar1 and iar2 are decaying to pointers to the first elements of the respective arrays. Since they are two distinct arrays, the pointer values are, of course, different and your comparison tests not equal.

To do an element-wise comparison, you must either write a loop; or use std::array instead

std::array<int, 5> iar1 {1,2,3,4,5}; std::array<int, 5> iar2 {1,2,3,4,5};  if( iar1 == iar2 ) {   // arrays contents are the same  } else {   // not the same  } 
like image 190
Praetorian Avatar answered Sep 28 '22 15:09

Praetorian