使用比较功能对列表进行排序
Sorting a list with compare function
我正在尝试对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
}
相关文章:
- C 中的排序列表
- 使用霍尔分区方案的快速排序算法返回原始未排序列表
- 带有额外参数的排序列表以进行比较功能
- 算法,用于查找获取排序列表所需的最小移动元素到结束步骤
- 迭代排序列表并计算不同的数字
- 维护多集中数字的排序列表和另一个集合中的累积总和
- 超过合并 k 排序列表的时间限制(leetcode)
- 正在检查排序列表中是否有一个范围内的数字
- O(N) 查找,但在排序列表上使用 upper_bound 时进行 O(log(N)) 比较
- 如何在只更改一个元素的情况下在排序列表中进行快速排序
- 返回指向排序列表的指针;C++中的链表
- 除了显示平均,最高和最低温度之外,有没有办法打印出整个排序列表
- 整数排序列表..TMP
- c++排序:具有相同数组值的排序列表
- 复制C++中未排序列表的构造函数
- 如何将元素添加到排序列表中..?(C++)
- 三维对象的Z排序列表
- 在我的排序列表中插入项目时出现问题
- 将节点插入到不带头指针的排序列表中
- 使用"pop_front"从排序列表中删除元素会导致崩溃