Re: problem with C++ sort algorithm
jo_atman@yahoo.com wrote:
Folks,
This strange problem is now solved, thanks to a programming illiterate
(but very sharp OR guy) at work. I guess showing you guys my compare
method would have helped you point it out too:
bool compareByCloseAndAlloc( State* s1, State* s2 )
{
int retVal = s2->getPDClose() - s1->getPDClose();
if ( retVal != 0 ) return retVal < 0;
return s1->getAllocation() - s2->getAllocation();
}
This problem is implementing this routine as if it were strcmp() and
having it return a -1, 0, or 1 depending on the relative order of the
operands. The actual requirement for this method is more simple:
returns true if the left operand is less than the right - and return
false in all other cases. Implemented with strcmp() behavior, the
function behaves nonsensically: reporting that a < b and b < a are both
true whenever a != b.
A more compact implementation would simply be:
bool compareByCloseAndAlloc( State* s1, State* s2 )
{
return s1->getPDClose() < s2->getPDClose() ?
true : s1->getPDClose() > s2->getPDClose() ?
false : s1->getAllocation() < s2->getAllocation();
}
I still honestly believe i did no wrong (i thought in C++, 0 was false,
every other number in the universe means true). before we close this
inane topic, maybe someone could clarify?
Yes, 0 converts to false - all other integer values to true.
Greg
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]