Problem w/ CListCtrl::SortItems
-
Did anyone experience any problems using CListCtrl::SortItems? I take this code from MSDN for the sorting callback function but it does not work.
// Sort the item in reverse alphabetical order. static int CALLBACK MyCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { // lParamSort contains a pointer to the list view control. CListCtrl* pListCtrl = (CListCtrl*) lParamSort; CString strItem1 = pListCtrl->GetItemText(lParam1, 0); CString strItem2 = pListCtrl->GetItemText(lParam2, 0); return strcmp(strItem2, strItem1); }
The result of this code when I apply to my list is that MyCompareProc is called exactly as many times as the item number but this is clearly not sufficient for a complet alphabetical order!!! Thus the order is wrong. Please help me!!!:(( Regards, Andrea -
Did anyone experience any problems using CListCtrl::SortItems? I take this code from MSDN for the sorting callback function but it does not work.
// Sort the item in reverse alphabetical order. static int CALLBACK MyCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { // lParamSort contains a pointer to the list view control. CListCtrl* pListCtrl = (CListCtrl*) lParamSort; CString strItem1 = pListCtrl->GetItemText(lParam1, 0); CString strItem2 = pListCtrl->GetItemText(lParam2, 0); return strcmp(strItem2, strItem1); }
The result of this code when I apply to my list is that MyCompareProc is called exactly as many times as the item number but this is clearly not sufficient for a complet alphabetical order!!! Thus the order is wrong. Please help me!!!:(( Regards, AndreaDe Nardis Andrea wrote: ...MyCompareProc is called exactly as many times as the item number but this is clearly not sufficient for a complet alphabetical order That depends on the sorting algorithm used. While some algorithms look at each item multiple times (e.g., bubble), others look at each item fewer times, or even just once. I suspect that the algorithm employed by
SortItems()
is based on Hoare's partition-exchange (i.e., quicksort) algorithm. As you add items to the control, a call toSetItemData()
should be made. For example, the item's data could be a pointer to aCMyObject
class. Then the comparison routine will look like:static int CALLBACK
MyCompareProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
CMyObject *p1 = (CMyObject *) lParam1;
CMyObject *p2 = (CMyObject *) lParam2;
CString str1 = p1->SomeString;
CString str2 = p2->SomeString;return strcmp(str1, str2);
}
Five birds are sitting on a fence. Three of them decide to fly off. How many are left?