使用比较功能对列表进行排序

时间:2014-04-15 19:53:32

标签: c++ list sorting

我正在尝试对list<CMail>进行排序(其中CMail是某个对象,对于此问题而言并不重要)。现在,我想对它进行排序。 我知道list有一个sort()函数,它使用标准运算符&lt;等,或给出比较功能。我确实有这样的功能。

我的功能

bool comp( const CMail & x ) const;
如果我们考虑a.comp(b),

返回; ,如果&lt; b,否则为假。 此函数也是CMail类的一部分,因此也是CMail名称空间的一部分。

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

temp.sort( CMail::comp );

其中temp是

list<CMail> temp;

但是,编译器不允许我说,

  

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

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

3 个答案:

答案 0 :(得分:5)

比较必须是二元仿函数,可以比较列表的所有元素。成员函数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);});

答案 1 :(得分:0)

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

答案 2 :(得分:0)

用作比较的非成员函数必须采用两个参数并返回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
}
相关问题