Link to home
Start Free TrialLog in
Avatar of mrwad99
mrwad99Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Sorting a CPtrArray: problems!

Ah hello.

I am trying to sort a CPtrArray of my own simple class.  This is based on the MSDN article at http://support.microsoft.com/kb/q216858/.  Code follows:

typedef int (__cdecl *GENERICCOMPAREFN)(const void * elem1, const void * elem2);
typedef int (__cdecl *STRINGCOMPAREFN)(const CMyClass * elem1, const CMyClass * elem2);

class CMyArray : public CPtrArray
{
public:
      void Sort(GENERICCOMPAREFN pfnCompare = Compare)
      {
            qsort ( this, GetSize(), sizeof ( CMyClass ), ( GENERICCOMPAREFN ) pfnCompare );
      }
protected:

      static int __cdecl Compare(const void * pMyClass1, const void * pMyClass2 )
      {
            if ( !pMyClass1 || !pMyClass2 ) return 0;
            CMyClass* pActualMyClass1 = (CMyClass*)pMyClass1;
            CMyClass* pActualMyClass2 = (CMyClass*)pMyClass2;

            return pActualMyClass1 ->m_dw < pActualMyClass2 ->m_dw;
      }
};

int main()
{
      CMyArray m_array;

      m_array.Add ( ( void*) new CMyClass ( 1 ) );
      m_array.Add ( ( void*) new CMyClass ( 3 ) );
      m_array.Add ( ( void*) new CMyClass ( 2 ) );

      m_array.Sort();

      return 0;
}

I would like to sort my array by the CMyClass object's DWORD member, in ascending order.

I am finding however that when Compare gets called, the DWORD value of the CMyClass object is like over 3386696!  Not what I initialised the object with when I added it to the array!  

Can someone explain what I am doing wrong here, and hence how to sort this array?
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

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
SOLUTION
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 mrwad99

ASKER

Both of those changes were required for it to work, so points split!

Thanks both :o)
Avatar of mrwad99

ASKER

Follow up at http:Q_23495395.html if anyone can help :)