优雅的做顺序比较的方法(C ++) [英] Elegant way to do sequential comparison (C++)

查看:151
本文介绍了优雅的做顺序比较的方法(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...
};

我想定义关系运算符( operator< 等),首先比较 a ,但如果 a 相等,比较 b ,但如果 b 相等,则比较 c 。 (我们假设 SomeOtherClass 已经有关系运算符定义的。)所以我有这样的事情

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.)

推荐答案

是的,有两种方法,我经常看到:

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

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

这篇关于优雅的做顺序比较的方法(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆