I have the following operator< that is supposed to sort first by a value, then by another value:
inline bool operator < (const obj& a, const obj& b)
{
if(a.field1< b.field1)
return true;
else
return a.field2 < b.field2;
}
I have the feeling this is incorrect and that you can't do that without another third comparaison test on the members variables, but I can't find any example where this doesn't work. So whould this really sort as expected? thanks
edit : I would have coded it as :
inline bool operator < (const obj& a, const obj& b)
{
if(a.field1< b.field1)
return true;
else if(a.field1> b.field1)
return false;
else
return a.field2 < b.field2;
}
are there any differences? I'm asking because I know mine is correct from experience but also longer than the first one
if( obj(2,1) < obj(1,2) )
. – Devote<
then for>
, only continuing to later checks in the==
case. Then for the final field you don't care about==
vs.>
so just return the<
result. Personally, I'd write each if statement on a single line, and not bother with theelse
asreturn
exits the function anyway. – Tarrance(a.f1 < b.f1)
then(b.f1 < a.f1)
. IIRC you get an automaticoperator>
when you defineoperator<
from the standard library, but this is OK even if that fails for some reason. – Tarrancereturn a.field1 != b.field1 ? a.field1 < b.field1 : a.field2 < b.field2;
(but with line breaks, which I can't put into a comment). – Lintwhite!=
then<
may seem more symmetric and may give more even performance (by slowing down the<
case to match the>
), but neither of those is a compelling issue for me. – Tarranceif
s, so there's no difference in readability there. The difference is that by using the ternary operator, thereturn
s aren't inif
s, and since there's only one branch, it's immediately clear that there isn't a branch where the return has been forgotten. – Lintwhiteif
/else
branches is the return. (But you still have to verify that everyif
has anelse
.) As for chaining ternary operators, this should be a standard C++ idiom, immediately recognizable by any competent practitioner. But it's not; in fact, I don't know of any textbook which presents it. (John Potter first showed it to me, and I'd been using C++ for over 10 years at the time.) Chained ternary operators, correctly formatted (which I can't do in a comment) are very readable. – Lintwhiteif
has anelse
for a very simple reason - my idiom doesn't useelse
at all. Remember - I prefer not to have the dependency on!=
. I don't have any nesting ofif
statements for this, just a chain of them. – Tarranceif
, I have a right as a reader to assume that it will be executed. – Lintwhitereturn
- there's alsobreak
,continue
,throw
- even a rare special case wheregoto
is justified. Sure, if theif
statement was non-trivial, thatreturn
becomes a hidden exit, and I'd agree with you. But when the entire body within a one-lineif
statement is eitherreturn true;
orreturn false;
, there's no excuse for failing to see that. – Tarrance