Jishnu Banerjee Jishnu Banerjee - 3 months ago 10
C++ Question

Can I compare 2 structures in C++?

I have simply declared a structure like this -

struct data{
int x,y;
};


Now I have declared 2 variables
a
&
b
of
data
type. I've assigned appropriate values to them. Now, I want to check if they are equal! I am trying to do like this -

data a,b;
a.x=12, a.y=24;
b.x=15, b.y=30;
if(a!=b)cout<<"a~b"<<endl;


But the compiler is giving me the following error on the
4th
line ->

error: no match for 'operator!=' (operand types are 'data' and 'data')


Where is the problem actually? Isn't this compare supported in C++?? Or I'm making any mistakes??

What is the exact and easiest way to do this?? Do I need to compare each of the elements in the structure separately?? Or there's any other smarter way??

Answer

C++ gives you attribute-by-attribute assignment implicitly, but no comparison for equality or ordering. The reason is "just because", don't look too hard into philosophy.

You need to provide those operators, if needed, by implementing yourself the operators explicitly, for example:

bool operator<(const Data& other) const {
    if (x < other.x) return true;
    if (x > other.x) return false;
    return y < other.y;
}

bool operator==(const Data& other) const {
    return x == other.x && y == other.y;
}

and so on.

Note also that defining for example == doesn't give you != automatically and defining < doesn't provide >= implicitly.