Re: comparison operator for STL sets
On May 7, 12:38 pm, "Christopher Dearlove"
<chris.dearl...@baesystems.com> wrote:
"Juha Nieminen" <nos...@thanks.invalid> wrote in message
[...]
I'm not claiming the following is the best organisation,
though I'd like to see one that's better (other than the loop
of course), especially if it can avoid doubling the number of
lines and using true and false explicitly.
if (primaryValue < rhs.primaryValue)
return true;
else if (rhs.primaryValue < primaryValue)
return false;
else if (secondaryValue < rhs.secondaryValue)
return true;
else if (rhs.secondaryValue < secondaryValue)
return false;
else if (tertiaryValue < rhs.tertiaryValue)
return true;
else if (rhs.tertiaryValue < tertiaryValue)
return false;
// etc...
else
return leastSignificantValue < rhs.leastSignificantValue;
Avoiding true and false is simple. In theory, anyway: the
results aren't always that pleasant. Basically, the rule for
any given element it:
return lhs.element < rhs.element
|| (! (rhs.element < lhs.element) &&
lhs.remainingElements < rhs.remainingElements ) ;
For the last element, it becomes simply:
return lhs.lastElement < rhs.lastElement ;
The problem is that when you expand this into a single function,
the alternating || and && imply that none of the parentheses can
be eliminated (or at least, I've not found a way to do so). So
you end up with some very hairy nesting.
Ideally, there's be some way of generating this using template
metaprogramming with template varargs---you'd give the list of
fields to be compared, and the template would do the rest. In
practice, I'm not sure---if nothing else, it's clear that you'd
have to give the list in the form of pointers to members (since
templates can't use just the name of a member as an argument),
which is a bit painful for starters. But other than that, it
should be workable.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34