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();
}
Translated to closer match your later example:
bool compareByCloseAndAlloc( State* s1, State* s2 )
{
int retVal = s2->getPDClose() - s1->getPDClose();
if ( retVal != 0 ) return retVal < 0;
retVal = s1->getAllocation() - s2->getAllocation();
return retVal != 0;
}
Well, this guy asked me why i'm returning a boolean (retVal < 0) on
line 2, but an integer on line 3. I said, well, C++ really uses ints as
bool, and that i could change the code to
bool compareByCloseAndAlloc( State* s1, State* s2 )
{
int retVal = s2->getPDClose() - s1->getPDClose();
if ( retVal != 0 ) return retVal < 0;
retVal = s1->getAllocation() - s2->getAllocation();
return retVal < 0;
}
but it wouldn't make a shred of a difference. And it did. It fixed the
problem.
Unless there's domain knowledge of the return values of getAllocation that
I'm missing, you've changed the last return from retVal != 0 to retVal < 0.
As a result, instead of returning true when s2->getAllocation() is smaller
than s1->getAllocation(), you're returning false.
--
Simon Farnsworth
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]