【问题标题】:Sorting a list with compare function使用比较功能对列表进行排序
【发布时间】:2014-05-30 08:47:47
【问题描述】:

我正在尝试对list<CMail> 进行排序(其中 CMail 是某个对象,对于这个问题的目的并不重要)。现在,我想整理一下。 我知道 list 有一个 sort() 函数,它要么使用标准 operator

我的功能

bool comp( const CMail & x ) const;

返回,如果我们考虑 a.comp(b); , 如果 a

现在,我想使用这个排序功能,我正在使用

temp.sort( CMail::comp );

其中 temp 是一个

list<CMail> temp;

但是,编译器不让我说

错误:非静态成员函数'bool CMail::comp(const CMail&) const'的使用无效

有人知道问题出在哪里吗?在此先感谢:)

【问题讨论】:

    标签: c++ list sorting


    【解决方案1】:

    用作比较的非成员函数必须接受两个参数并返回 bool

    bool comp( const CMail & x1, const CMail& x2) {
        return 1;
    }
    
    int main(int argc, char** argv) {
        std::list<CMail> l;
        l.assign( 4, CMail());
        l.sort( &comp);
    }
    

    在 C++11 中,您可以使用 lambda 函数。这是调用成员函数CMail::comp的示例:

    int main(int argc, char** argv) {
        std::list<CMail> l;
        l.assign( 4, CMail());
        l.sort( [](const CMail& x1, const CMail& x2) { return x1.comp( x2);});
                                                               ^^^^ //member function
    }
    

    【讨论】:

      【解决方案2】:

      将您的 comp 函数更改为静态。您正在尝试在没有实例化对象的情况下访问它。

      【讨论】:

        【解决方案3】:

        比较必须是一个可以比较列表中所有元素的二元仿函数。成员函数CMail::comp 不满足这一点。尝试非会员。这可以通过您的成员CMail::comp 来实现:

        bool comp(const CMail& lhs, const CMail& rhs )
        {
          return lhs.comp(rhs);
        }
        

        然后

        temp.sort(comp);
        

        或者,使用 lambda:

        temp.sort([](const CMail& lhs, const CMail& rhs ){return lhs.comp(rhs);});
        

        【讨论】:

        • 谢谢。我想我现在明白问题所在了。我创建了另一个函数,期望 2 个 CMail 类型的参数,但是,编译器现在说:没有已知的参数 1 从 '' 到 'bool (CMailBox::*)(const CMail&, const CMail&)const 的转换我可以用一些演员或其他东西来改变类型吗?
        • @MichalKučera 您的函数应该是非成员。否则你必须使用std:bind
        • 现在一切正常:)。非常感谢您的先生
        猜你喜欢
        • 2011-07-09
        • 2013-10-03
        • 1970-01-01
        • 2013-02-13
        • 1970-01-01
        • 2018-09-10
        • 1970-01-01
        • 2011-01-26
        • 2020-12-03
        相关资源
        最近更新 更多