Page 1 of 1

[MFC] Cum sortez un CStringArray?

Posted: 27 Apr 2013, 08:14
by Ovidiu Cucu
Q: Cum sortez un CStringArray (CArray, CTypedPtrArray, CObArray, CByteArray, CDWordArray, CPtrArray, CWordArray sau CUIntArray)?

A:
  1. Folosind functia std::sort din STL.
    Exemplu

    Code: Select all

    #include <algorithm>
    // ...
    
       CStringArray arr;
       arr.Add(_T("costel"));
       arr.Add(_T("Ana"));
       arr.Add(_T("Gigel"));
       arr.Add(_T("Zoe"));
       arr.Add(_T("gigel")); 
       arr.Add(_T("Costel"));
       arr.Add(_T("zoe"));
       arr.Add(_T("ana"));
       
       // sort descending, case sensitive
       std::sort(arr.GetData(), arr.GetData() + arr.GetSize(), StlCompareCStringDesc);
    Unde functia de coparare pasata lui std::sort are forma:

    Code: Select all

    bool StlCompareCStringDesc(const CString& left, const CString& right)
    {
       return left > right;
    }
    Exemplul de mai sus, face o sortare descrescatoare, case sensitive (face distinctie intre litere mari si mici).
    Dupa sortare, array-ul arata asa:
    CStringArray - sort descending - case sensitive.jpg
    CStringArray - sort descending - case sensitive.jpg (31.66 KiB) Viewed 8883 times
  2. Folosind functia qsort din biblioteca C standard.
    Exemplu

    Code: Select all

       CStringArray arr;
       arr.Add(_T("costel"));
       arr.Add(_T("Ana"));
       arr.Add(_T("Gigel"));
       arr.Add(_T("Zoe"));
       arr.Add(_T("gigel")); 
       arr.Add(_T("Costel"));
       arr.Add(_T("zoe"));
       arr.Add(_T("ana"));
       
       // sort ascending, non case sensitive
       qsort(arr.GetData(), arr.GetSize(), sizeof(CString*), CrtCompareCStringNoCaseAsc);
    De data aceasta functia de comparare (pentru sortare crescatoare, non case sensitive) e de forma:

    Code: Select all

    int CrtCompareCStringNoCaseAsc(const void* left, const void* right)
    {
       return ((CString*)left)->CompareNoCase(*((CString*)right));
    }
    I fine, array-ul sortat arata acum asa:
    CStringArray - sort ascending - non case sensitive.jpg
    CStringArray - sort ascending - non case sensitive.jpg (31.54 KiB) Viewed 8883 times
Note
  • Pentru simplitate, am dat in exemplu functii de comparare globale. Pot fi la fel de bine functii membre statice sau sau, in cazul lui std::sort, functori sau expresii lambda (C++11).
  • Pana la a decide necesitatea sortarii unui sir intr-un container, trebuie de vazut daca este neaparata nevoie. De exemplu, controlul Windows lisview (SysListView32), implementat in MFC cu clasa CListCtrl, are functie de sortare built-in (vezi CListCtrl::SortItems).
  • Acelasi principiu se aplica la toate tipurile de array-uri MFC: CArray, CStringArray, CTypedPtrArray, CObArray, CByteArray, CDWordArray, CPtrArray, CWordArray si CUIntArray.
  • Cum se afiseza elementele unui aray MFC in fereastra watch, se arata in articolul precedent (vezi link-ul de mai jos).
Vezi si
<< Back to MFC index