Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array contents equality in C++

Tags:

c++

Is there a way to get the equality operators to work for comparing arrays of the same type?

For example:

int x[4] = {1,2,3,4};
int y[4] = {1,2,3,4};
int z[4] = {1,2,3,5};
if (x == y) cout << "It worked!"

I'm aware that as is, it's just comparing pointer values - but I was hoping there's some kind of typedef trick or something like that so it wouldn't need a loop or a memcmp call.

like image 946
John Humphreys Avatar asked Nov 27 '22 00:11

John Humphreys


2 Answers

You can use standard equal algorithm

if (std::equal(x,x+4,y)) cout << "It worked!";
like image 83
Vladimir Avatar answered Dec 26 '22 19:12

Vladimir


Use std::equal as:

if(std::equal(x, x+ xsize, y)) std::cout << "equal";

It checks equality of elements in the same order. That means, according to std::equal the following arrays are not equal.

int x[4] = {1,2,3,4};
int y[4] = {1,2,4,3}; //order changed!
like image 38
Nawaz Avatar answered Dec 26 '22 20:12

Nawaz