开发者

How to Sort CTypedPtrList in C++ or MFc?

I want some template classes like sort etc is used to sort the CTyped开发者_运维百科PtrList.


This Sample will sort CTypedPtrArray :

    typedef  CTypedPtrArray<CPtrArray , CLog *> CLogData;
    CLogData tLogData;
    CLog *t1Log , * t2Log;
    bool bChanged = true;
if (tLogData.IsEmpty()) 
    return;
long int i, j;
for (i = 0 ; i < m_nCount - 1  ; i++) 
{
    for( j = i + 1; j < m_nCount ; j++ )
    {
        t1Log = tLogData.GetAt( i);
        t2Log = tLogData.GetAt( j ) ;
        if (strcmp(t1Log->GetThreadName() , t2Log->GetThreadName()) > 0) 
        {
              tLogData.SetAt( i  , t2Log );
              tLogData.SetAt( j ,  t1Log );

        }
    }
}


karthik's solution will not work for CTypedPtrList, as CTypePtrList does not support .GetAt() and .SetAt() ; here's a solution using pointer lists instead of arrays.

typedef CTypedPtrList<CPtrList, CMyObject*> ObjectList;

// sort object list using CMyObject's 'order' attribute
ObjectList* oldList = Objects;
Objects = new ObjectList();
for (POSITION pos1 = oldList->GetHeadPosition(); pos1 != NULL;)
{
    CMyObject *obj1 = oldList->GetNext(pos1);
    POSITION pos2 = Objects->GetHeadPosition();
    bool inserted = false;
    while (pos2 != NULL)
    {
        POSITION currentPos = pos2;
        CMyObject *obj2 = Objects->GetNext(pos2);
        if (obj1->GetOrder() < obj2->GetOrder())
        {
            Objects->InsertBefore(currentPos, obj1);
            pos2 = NULL;
            inserted = true;
        }
    }
    if (!inserted) Objects->AddTail(obj1);
}
delete oldList; 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜