Order MFC array with qsort()






4.54/5 (13 votes)
How to order an MFC array using standard function qsort().
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;
// ... Add some strings to 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; //With this two operator will be possible to //order using default c_arraysort sorting function bool operator<(const myClass& elem2) const { return str < elem2.str;} bool operator>(const myClass& elem2) const { return str > elem2.str;} // Custom ascending ordering function (order by str or by n) 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; // Sort using operator < c_arraysort<CArray<myClass,myClass>,MyClass>(myArray,sort_asc); // Sort using operator > c_arraysort<CArray<myClass,myClass>,MyClass>(myArray,sort_desc); // Sort using custom function 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 byqsort
) and the custom one (used byc_arraysort
), - function
CArray::GetData()
is used to get a pointer to the first array element passed as first parameter inqsort()
, Ctor
calls sorting function, in this mode using the class is like calling a function.