ch52jb
asked on
STL List sorting
I have a list of pointers to objects and I need to sort them based on a member variable. The code I have is:
std::list<CMyClass *> myList;
CMySorter sorter;
list.sort(sorter)
The sorter class is:
class CMySorter : public
std::greater<CMyClass *>
{
bool operator()(
const CMyClass *pFirst,
const CMol *pSecond) const
{
if(pFirst->Count() >
pSecond->Count())
return true;
else
return false;
}
}
This all works fine in debug mode (I'm using VC++ 6) but in release mode, it doesn't sort the list. Any ideas why or how I can get round this would be greatly appreciated.
Jim
std::list<CMyClass *> myList;
CMySorter sorter;
list.sort(sorter)
The sorter class is:
class CMySorter : public
std::greater<CMyClass *>
{
bool operator()(
const CMyClass *pFirst,
const CMol *pSecond) const
{
if(pFirst->Count() >
pSecond->Count())
return true;
else
return false;
}
}
This all works fine in debug mode (I'm using VC++ 6) but in release mode, it doesn't sort the list. Any ideas why or how I can get round this would be greatly appreciated.
Jim
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
How would I implement this in my code. Do I put the above code in my header file and call
list.sort(std::greater<CMy Class*>)
or is it implemented another way?
Many thanks
Jim
list.sort(std::greater<CMy
or is it implemented another way?
Many thanks
Jim
Basically just like what you've done. the only difference is that you've specialed greater<> for your class rather than defining a new class derived from it. This is because the derived portion will not be used by the sort() function.
std::list<CMyClass *> myList;
greater<CMyClass *> sorter;
myList.sort(sorter)
std::list<CMyClass *> myList;
greater<CMyClass *> sorter;
myList.sort(sorter)
ASKER
Thank you very much, it's all now working fine. I'm saved from a day of swearing at VC++!
Many thanks
Jim
Many thanks
Jim
template<> class std::greater<CMyClass *>
{
bool operator()(const CMyClass *pFirst,
const CMol *pSecond) const
{
return pFirst->Count() > pSecond->Count();
}
};
(Note the way that the comparison has been simplified too.)