Using Lambdas in MFC Applications – Sorting Arrays

Beginning with Visual Studio 2010 which supports lambda expressions introduced by C++11 standard, you can handily sort an MFC array like in the following example:

Sorting CStringArray by using a lambda expression

// Example #1
    // ...
    CStringArray arr;
    arr.Add(_T("John"));
    arr.Add(_T("Zorro"));
    arr.Add(_T("Sandy"));
    arr.Add(_T("Jimmy"));
    // ...

    bool bAscending = true;
    // ...

    std::sort(
        arr.GetData(),                                           // position of first element
        arr.GetData() + arr.GetSize(),                           // position one past the final element 
        [bAscending]                                             // lambda introducer
        (const CString& left, const CString& right)              // lambda formal parameters list
        { return bAscending ? (left < right) : (left > right); } // lambda body
        );
    // ...

Of course, you can write similar code for other types of MFC arrays like CArray, CUIntArray, and so on.
But also you can easily write a kind of “generic lambda” in order to sort any type of MFC arrays.

Using decltype to sort any type of MFC array

// Example #2
    // ...
    std::sort(
        arr.GetData(), 
        arr.GetData() + arr.GetSize(),
        [bAscending]
        (decltype(*arr.GetData()) left, decltype(*arr.GetData()) right)
        { return bAscending ? (left < right) : (left > right); }
        );
    // ...

That’s pretty cool… However would be nice to be possible to get rid of “wordy” constructions like “decltype(*arr.GetData())” in the lambda’s formal parameters list. Good news! There is a proposal for next C++ standards: using auto type-specifier in order to make generic lambda expressions (which accept any type of arguments). And that is already supported in Visual Studio 2015.

Using generic (polymorphic) lambda expressions

    // Example #3
    std::sort(
        arr.GetData(),
        arr.GetData() + arr.GetSize(),
        [bAscending]                                         
        (auto left, auto right)                                
        { return bAscending ? (left < right) : (left > right); }
        );

Notes

  • Some people may claim that using MFC collection classes is obsolete and must use STL containers instead. That’s an old subject of arguing but it’s not in scope of this short article.
    It simply presents how to sort MFC arrays by using lambda expressions.

References and related articles

1 thought on “Using Lambdas in MFC Applications – Sorting Arrays”

  1. Nice post, thanks for sharing. It’s easy to forget that GetData() on an MFC container is compatible with a std algorithm expecting an iterator.

    Reply

Leave a Comment