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

Sorting a list with compare function

本文关键字:排序 列表 比较 功能      更新时间:2023-10-16

我正在尝试对list<CMail>进行排序(其中CMail是一些对象,对于这个问题来说并不重要(。现在,我想整理一下。我知道list有一个sort((函数,它要么使用标准运算符<或给定的比较函数。我确实有这样的功能。

我的功能

bool comp( const CMail & x ) const;

返回,如果我们确实考虑a.comp(b(,如果<b、 否则为false。此函数也是CMail类的一部分,因此也是CMail命名空间的一部分。

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

temp.sort( CMail::comp );

其中temp是

list<CMail> temp;

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

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

有人看到问题出在哪里了吗?提前感谢:(

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

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

用作比较的非成员函数必须接受两个参数并返回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
}