problem in std::sort with self define compare function (VC6)

Started by
4 comments, last by iMalc 18 years, 4 months ago
see the code below, The compare function got a dirty pointer when it swapped the elements. The error also about the size of vector. it will occurs the error when the size more than 20. what's the problem? is it the VC6 standard library bug? and how to fix it? #include "stdafx.h" #include <vector> #include <algorithm> #include <tchar.h> #include <windows.h> typedef struct _SIMInfo { BOOL bOnline; } SIMInfo; std::vector<SIMInfo*> m_arr; bool CompareFriend(SIMInfo * infox, SIMInfo * infoy) { bool b = infox->bOnline; bool b2 = infoy->bOnline; return true; } int main(int argc, char* argv[]) { for (int i = 0; i < 50; ++i) { SIMInfo * pinfo = new SIMInfo; memset(pinfo, 0, sizeof(SIMInfo)); m_arr.push_back(pinfo); } std::sort(m_arr.begin(), m_arr.end(), CompareFriend); return 0; }
Advertisement
I've discovered this with VC6's STL as well. If your compare function ever returns true for both a < b and b < a, then it can cause a fatal error. You can fix it by making sure your compare function makes sense :)
Errrr. I would rewrite your compare function like this:
bool CompareFriend(const SIMInfo * infox, const SIMInfo * infoy){   bool b = infox->bOnline;   bool b2 = infoy->bOnline;   return b < b2;}
oh thank you~
my original compare function is below

bool CompareFriend(SIMInfo * infox, SIMInfo * infoy)
{
if (infox->bOnline && !infoy->bOnline)
return true;
else if (!infox->bOnline && infoy->bOnline)
return false;
else
{
int nCmpResult = _tcscmp(infox->szName, infoy->szName);
if (nCmpResult > 0)
return false;
else if (nCmpResult <
oh thank you~
my original compare function is below

<textarea>
bool CompareFriend(SIMInfo * infox, SIMInfo * infoy)
{
if (infox->bOnline && !infoy->bOnline)
return true;
else if (!infox->bOnline && infoy->bOnline)
return false;
else
{
int nCmpResult = _tcscmp(infox->szName, infoy->szName);
if (nCmpResult > 0)
return false;
else if (nCmpResult < 0)
return true;
else
return true; <- the problem is here, should instead to false
}
}
</textarea>
Please log in and use [source][/source] tags.
Quote: return true; <- the problem is here, should instead to false
The comment you have made on one of the lines is indeed correct. It must be false there because you're supposed to only return true when infox is less than infoy. When they are equal, they are not less than.

Try using this:
bool CompareFriend(SIMInfo * infox, SIMInfo * infoy){    if (infox->bOnline && !infoy->bOnline)        return true;    else if (!infox->bOnline && infoy->bOnline)        return false;    else        return (_tcscmp(infox->szName, infoy->szName) < 0);}
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement