Link to home
Start Free TrialLog in
Avatar of ch52jb
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
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

The way to make this work is to specialize the greater<T>  template class for your type.   I believe the syntax for this is

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.)
Avatar of ch52jb

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<CMyClass*>)

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)
Avatar of ch52jb

ASKER

Thank you very much, it's all now working fine.  I'm saved from a day of swearing at VC++!

Many thanks

Jim