Archive

Archive for December, 2008

How to sort CAtlArray using qsort

December 8th, 2008 No comments

Unfortunately, ATL does not come with a built-in sorting algorithm. So the choices you have are: a) roll your own sort function or b) build your app with stdlib support and use the super easy qsort funtion:

CAtlArray<MyFile> dynamic_array;
//...
qsort( dynamic_array.GetData(), dynamic_array.GetCount(), sizeof( MyFile ), (int(*)(const void*, const void*))MyFileSorter );
//...
int __cdecl MyFileSorter( MyFile *p1, MyFile *p2 )
{
    if ( p1->x == p2->x )
        return 0;
    else
        return p1->x > p2->x ? 1 : -1;
}

In case your sorting callback’s signature is identical to int __cdecl ( const void*, const void* ), there is no need to cast the last parameter to the qsort function.
There is one important thing to note: the callback should only return -1, 0, and 1. So instead of doing a simple subtraction of the values you want to compare, you should add a boolean comparison which only returns one of the three values.