按函子错误排序

时间:2012-10-30 08:37:30

标签: c++ sorting functor

想知道是否有人可以帮助我。下面的代码给了我这个错误: 致命错误C1903:无法从之前的错误中恢复;停止编译

template <class T>
class CompareList
{
public:

    CompareList( const long& lBlobFeature, const bool& bIsAscending )
{
    ...
}


bool operator()( T &lhs, T &rhs ) 
{

    double dFirstValue  = lhs.GetValue( ... );
    double dSecondValue = rhs.GetValue( ... );


    if( m_bIsAscending )   // Sort Ascending.
    {
        if( dFirstValue < dSecondValue )
            return true;
        else 
            return false;
    }
    else                   // Sort Descending.
    {
        if( dFirstValue > dSecondValue )
            return true;
        else 
            return false;
    }
}

};


CVParentList     *m_pList;
m_pList = new CVChildList[ nBlobs ]; //CVChildList is a derived class of CVParentList

std::sort( m_pList, m_pList+GetBlobsNumber(), CompareList <CVChildList> ( lBlobFeature, TRUE) );

修改 我很抱歉,实际上这是第一个错误: 错误C2664:'bool CompareList :: operator()(T&amp;,T&amp;)':无法将参数1从'CVParentList'转换为'CVChildList&amp;'

“致命错误C1903:无法从之前的错误中恢复;停止编译” 之后,我只看到了最后一条错误消息。很抱歉。

2 个答案:

答案 0 :(得分:1)

可能需要将const引用传递给您的仿函数,因为比较不应更改要比较的对象。编译器可能要求也可能不要求。将仿函数签名更改为

bool operator()(const  T& lhs, const T& rhs ); 

答案 1 :(得分:1)

您的比较器或动态列表。需要改变。您可以抛弃比较器的模板部分,只需将其声明为CVParentList比较器:

class CompareList
{
public:
    CompareList(long lBlobFeature, bool isAscending);

    bool operator()(const CVParentList& left, const CVParentList& right) const
    {
        bool ans = false;
        // your comparison code goes here
        return ans;
    }
private:
    bool m_bIsAscending;
};

并调用你的std :: sort&lt;&gt;正如你在做而没有模板参数

std::sort( m_pList, m_pList+GetBlobsNumber(), CompareList( lBlobFeature, TRUE) );

您还可以分配列表,对其进行排序,然后在完成后向下转发列表:

CVParentList *m_pList = new CVChildList[ nBlobs ];
std::sort( (CVChildList *)m_pList, (CVChildList *)m_pList+GetBlobsNumber(), CompareList<CVChildList> ( lBlobFeature, TRUE) );

但我真的建议您使用第一个选项。