65.9K
CodeProject 正在变化。 阅读更多。
Home

对智能列表类的补充

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.79/5 (18投票s)

2007年4月2日

CPOL
viewsIcon

39675

downloadIcon

275

本文介绍了 Simon Hughes 的 SmartList 代码以及一些新功能

引言

本文介绍了 Simon Hughes 的 SmartList 的代码,并添加了一些我新增的功能。这段代码是完全免费的(就像之前一样),你可以随意使用,但请在代码中保留我们(Simon 和我的)电子邮件地址,以便接收可能的错误报告。

本文介绍了一系列列表类,它们封装了 MFC 列表类,并添加了一些新功能。这段代码(包含新增功能)已经在我的几个项目中被充分测试过。但是,如果有人发现任何错误或改进建议,请发送给我,我会尽快修复它们。

新增功能

BOOL FindAndRemoveElement (const ARG_TYPE searchValue);

BOOL FindAndReplaceElement (const ARG_TYPE searchValue, const ARG_TYPE 
    newValue);

BOOL operator== (const CMyList &temp)

// Find and Remove a TYPE object of the list, searching by ARG_TYPE
template <class TYPE, class ARG_TYPE> 

BOOL CMyList<TYPE, ARG_TYPE>::FindAndRemoveElement(const ARG_TYPE 
    searchValue) 
{   
    ASSERT_VALID (this); 

    POSITION pos = Find (searchValue); 
    if (pos != NULL)    // When found, remove element 
    {   
        RemoveAt(pos); 
        return TRUE;
    } 
    else 
        return FALSE; 
} 

// Find and Replace a TYPE object of the list, searching by ARG_TYPE
template <class TYPE, class ARG_TYPE> 
BOOL CMyList<TYPE, ARG_TYPE>::FindAndReplaceElement(const ARG_TYPE 
    searchValue, const ARG_TYPE newValue) 
{
    ASSERT_VALID (this); 

    POSITION pos = Find (searchValue); 
    if (pos != NULL)    // When found, replace old element with new one 
    {    
        SetAt (pos, newValue); 
        return TRUE;
    } 
    else 
        return FALSE; 
}

// Equality operator for the whole list (CMyList1 == CMyList2)
template <class TYPE, class ARG_TYPE> 
BOOL CMyList<TYPE, ARG_TYPE>::operator== (const CMyList &temp) 
{   
    ASSERT_VALID (this);
    ASSERT_VALID (&temp);

    int nMatches = 0; // To have the number of matches

    if(this == &temp) // Check for self assignment
        return TRUE;

    // If one list has different number of elements, can't be equal
    if (GetCount () != temp.GetCount ())
        return FALSE;

    POSITION posThis = GetHeadPosition ();
    POSITION posOther = temp.GetHeadPosition ();
    while ((posThis)&&(posOther))
    {    // This is to look for in the same place in both lists
        TYPE thisTYPE = (TYPE)GetNext(posThis);
        TYPE otherTYPE = (TYPE)temp.GetNext(posOther);

        //This presupposes that TYPE object has implemented the operator==
        if (thisTYPE == otherTYPE)
            nMatches++;
        else
        break;
    }
    // If all the objects in the list were equal… the lists are equal
    if (nMatches == GetCount ()) 
        return TRUE;
    return
        FALSE; 
}
© . All rights reserved.