Writing an operator< () for a struct appears to be clearer than writing the classical trivalue compare.
for example, to sort the following
struct S {
int val;
};
you can write an operator< ()
bool operator< ( const S &l, const S &r ) {
return l.val < r.val;
}
or, a trivalue function (usually in the following fashion )
int compare( const S &l, const S &r ) {
if( r.val > l.val ) return 1;
if( r.val < l.val ) return -1;
return 0;
}
The former is clearer, therefore you can say there's better code quality. The latter forces you to think of 3 cases, which complicates code.
But this thought is a bit deceiving in more complex structures:
struct S {
int x;
int y;
};
the following is clear, and begginners tend to write it like so
bool operator< ( const S &l, const S &r ) {
if( l.x < r.x ) return true;
if( l.y < r.y ) return true;
return false;
}
but it's wrong ! You can't sort correctly with this !
And it takes some time to think that you actually have to write it like so
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;
}
for it to work correctly.
Can you, and do you write this sort of compare function in a nicer/clearer manner ? The old trivalue compare function at least 'forced' you into thinking about >, <, and == cases.