Introduction
MFC CArray doesn't implement an ordering function, but with a little trick it is possible to order a CArray based-class (or a CStringArray, CDWordArray etc.) using the fast qsort() function included in stdlib.
This template class allows to order an array of every type by declaring the type of array and the type of every element contained into. For example, to sort a CStringArray using the default ascending function:
CStringArray array;
c_arraysort<CStringArray,CString>(array,sort_asc);
in the same way is possible to order a custom struct (or class):
class myClass
{
public:
myClass() {}
CString str;
long n;
bool operator<(const myClass& elem2) const
{ return str < elem2.str;}
bool operator>(const myClass& elem2) const
{ return str > elem2.str;}
static int _cdecl sort_by_str(const myClass* elem1,const myClass* elem2)
{ return elem1->str < elem2->str ? -1 : 1; }
static int _cdecl sort_by_n(const myClass* elem1,const myClass* elem2)
{ return elem1->n < elem2->n ? -1 : 1; }
};
CArray<myClass,myClass> myArray;
c_arraysort<CArray<myClass,myClass>,MyClass>(myArray,sort_asc);
c_arraysort<CArray<myClass,myClass>,MyClass>(myArray,sort_desc);
c_arraysort<CArray<myClass,myClass>,MyClass>(myArray,myClass::sort_by_str);
c_arraysort<CArray<myClass,myClass>,MyClass>(myArray,myClass::sort_by_n);
Implementation
Class is quite simple:
- two
typedef are used only to prevent long cast between generic compare function prototype (used by qsort) and the custom one (used by c_arraysort),
- function
CArray::GetData() is used to get a pointer to the first array element passed as first parameter in qsort(),
Ctor calls sorting function, in this mode using the class is like calling a function.