Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to do sequential comparison (C++)

Suppose I have a class with several member variables:

class MyClass{
    std::string a;
    int b;
    SomeOtherClass c;
    // some stuff...
public:
    // some other stuff...
};

I want to define relational operators (operator<, etc.) that first compare a, but if the a are equal, compare b, but if the b are equal, compare c. (We assume SomeOtherClass already has relational operators defined.) So I have something like

bool operator==(MyClass param){
    return (a == param.a) && (b == param.b) && (c == param.c);
}

bool operator<(MyClass param){
    if(a < param.a) return true;
    if(a > param.a) return false;
    if(b < param.b) return true;
    if(b > param.b) return false;
    if(c < param.c) return true;
    return false;
}

and so on. Is there any more elegant way to do this? It seems quite cumbersome, especially if there are lots of member variables to be compared. (Boost is an option.)

like image 996
jcai Avatar asked Dec 07 '25 03:12

jcai


2 Answers

Yes, there's two ways I've seen commonly:

bool operator<(MyClass param){
    if(a != param.a) return a<param.a;
    if(b != param.b) return b<param.b;
    return c<param.c;
} 

http://coliru.stacked-crooked.com/view?id=dd70799c005e6e99c70ebda552161292-c96156d6cc95286981b0e9deef2eefae

or

bool operator<(MyClass param){
    return std::tie(a, b, c)<std::tie(param.a, param.b, param.c);
}

http://coliru.stacked-crooked.com/view?id=00278eaca0d73b099fcd8edf87b5057b-c96156d6cc95286981b0e9deef2eefae

like image 62
Mooing Duck Avatar answered Dec 09 '25 00:12

Mooing Duck


Sure, you can use std::tie for this:

#include <tuple>

bool operator<(const MyClass& lhs, const MyClass& rhs)
{
  return std::tie(lhs.a, lhs.b, lhs.c) < std::tie(rhs.a, rhs.b, rhs.c);
}
like image 24
juanchopanza Avatar answered Dec 08 '25 22:12

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!