# CodeGuru Technical FAQs > CodeGuru Individual FAQs >  MFC STL: How can I sort a 'CArray' (or 'CStringArray', 'CIntArray', etc.)?

## Gabriel Fleseriu

*Q:* How can I sort a 'CArray' (or 'CStringArray', 'CIntArray', etc.)?

*A:* If the CxxxArray's items can be compared, then use 'std::sort':

*Ascending:*



```
#include <algorithm>

CArray<int, int&> MyCArray;
CStringArray MyStringArray;

// Sort the CArray of ints
std::sort(MyCArray.GetData(), MyCArray.GetData() + MyCArray.GetSize());

// Sort the CStringArray
std::sort(MyStringArray.GetData(), MyStringArray.GetData() + MyStringArray.GetSize());
```

*Descending:*

You need to supply a comparison function.



```
#include <algorithm>

bool SortDescendingInt(const int& x, const int& y)
{
   return x > y;
}

bool SortDescendingString(const CString& s1, 
                          const CString& s2)
{
   return s1 > s2;
}

CArray<int, int> MyCArray;
CStringArray MyStringArray;

// Sort the CArray of ints
std::sort(MyCArray.GetData(), 
          MyCArray.GetData() + MyCArray.GetSize(), 
          SortDescendingInt);

// Sort the CStringArray
std::sort(MyStringArray.GetData(), 
          MyStringArray.GetData() + MyStringArray.GetSize(),
          SortDescendingString);
```

FAQ contributed by: [Paul McKenzie]

----------


## ovidiucucu

One alternative solution is to use the ANSI C function qsort 

Next example sorts ascending, non case-sensitive the elements of a CStringArray.


```
   CStringArray arr;

   arr.Add(_T("barbu")); // just for example
   arr.Add(_T("ANNA"));
   arr.Add(_T("ZOE"));
   arr.Add(_T("BUBU"));
   arr.Add(_T("bob"));
   arr.Add(_T("MIKI"));
   // ...

   qsort(arr.GetData(), arr.GetSize(), sizeof(CString*), CompareAscNoCase);
```



```
int CompareAscNoCase(const void* left, const void* right)
{
    return ((CString*)left)->CompareNoCase(*((CString*)right));
}
```

----------


## ovidiucucu

Beginning with *Visual Studio 2010*, can also handily use *lambda expressions* like in the following example:



```
    // ...
 
    bool bAscending = true;
    // ...
 
    std::sort(arr.GetData(), arr.GetData() + arr.GetSize(),                           
        [bAscending]                                             // lambda introducer
        (const CString& left, const CString& right)              // lambda formal parameters list
        { return bAscending ? (left < right) : (left > right); } // lambda body
        );
    // ...
```



See also:
 Using Lambdas in MFC Applications – Part 1: Sorting Arrays

----------

