I am trying to implement a comparator function, and coming from a JavaScript background attempted to chain them like so:
int MyClass::compare(MyClass & other) {
return MyClass.x.compare(other.x) || MyClass.y.compare(other.y);
}
That is, compare the objects' x
values, and if they are equal compare the objects' y
values.
I immediately realized this wouldn't work, because the OR function in c++ returns a bool rather than the last evaluated value.
Other than literally writing an if statement, like
int result = MyClass.x.compare(other.x);
if (result) {
return result;
}
result = MyClass.y.compare(other.y);
return result;
, is there is a concise way to write this expression?