Comparing 2 arrays

I need to compare 2 arrays to see if they have the same values (even if they are in a different order)

e.g array1[5]={1,6,5,4,3}
array2[5]={6,5,3,4,1}

both arrays have the same values.

how do i create a program that compares to arrays (input by user) and returns a boolean true or false if they have/dont have the same values.
My general advice is to use std::set instead. (Alternatively multiset if you need to support duplicates).

http://cplusplus.com/reference/stl/set/

Otherwise:

If it's possible to change the arrays, you can sort them first, and then check that they are equal. If you can't modify the arrays, you can create sorted copies.

Without sorting, one way might be to count the number of occurences of each value in both arrays:

1
2
3
4
5
6
7
8
for (int i = 0; i < 5; i++) {
  int val = array1[i];
  int count1 = std::count(array1, array1+5, val);
  int count2 = std::count(array2, array2+5, val);
  if (count1 != count2)
    return false; // not equal
}
return true; // equal 
Topic archived. No new replies allowed.