优雅的做顺序比较的方法(C ++) [英] 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...
};
我想定义关系运算符( 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;
}
或
bool operator<(MyClass param){
return std::tie(a, b, c)<std::tie(param.a, param.b, param.c);
}
这篇关于优雅的做顺序比较的方法(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!