为结构编写运算符< () 似乎比编写经典的三值比较更清晰。
例如,对以下内容进行排序
struct S {
int val;
};
你可以写一个运算符< ()
bool operator< ( const S &l, const S &r ) {
return l.val < r.val;
}
或者,三值函数(通常采用以下方式)
int compare( const S &l, const S &r ) {
if( r.val > l.val ) return 1;
if( r.val < l.val ) return -1;
return 0;
}
前者更清晰,因此可以说代码质量更好。 后者迫使您考虑 3 种情况,这会使代码复杂化。
但是这个想法在更复杂的结构中有点欺骗:
struct S {
int x;
int y;
};
下面写的很清楚,初学者往往这样写
bool operator< ( const S &l, const S &r ) {
if( l.x < r.x ) return true;
if( l.y < r.y ) return true;
return false;
}
但这是错误的!你不能用这个正确排序!
这需要一些时间来思考 你实际上必须这样写
bool operator< ( const S &l, const S &r ) {
if( l.x < r.x ) return true;
if( l.x > r.x ) return false;
if( l.y < r.y ) return true;
if( l.y > r.y ) return false;
return false;
}
让它正常工作。
您能以更好/更清晰的方式编写这种比较函数吗? 旧的三值比较函数至少“迫使”您考虑 >、< 和 == 情况。
最佳答案
如果我不关心性能或编译器涌出,我倾向于使用这个:
return make_tuple(l.x, l.y, ...) < make_tuple(r.x, r.y, ...);
对于拷贝版本来说稍微便宜一点:
return tie(cref(l.x), cref(l.y), ...) < tie(cref(r.x), cref(r.y), ...);
顺便说一句,第二个版本也适用于左值。
关于c++ - 如何编写比三值比较函数更整洁的 operator() 或 less-than-functor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3864948/