通过自定义comperator对STL列表进行排序 [英] Sorting STL list by custom comperator

查看:69
本文介绍了通过自定义comperator对STL列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿伙计们,我看了一些排序示例,我认为我必须构建一个返回bool的comperator,以保持我的列表按该值排序。


这里有相关的代码:

Hey guys, i looked at some sorting examples, and i thought i jsut had to build a comperator which returns bool, in order to keep my list sorted by that value.

here''s the relevent code:

展开 | 选择 | Wrap | 行号

推荐答案

这是一个页面列表的排序功能。 sort方法可以使用自定义比较器对列表进行排序,但为什么会这样呢?您按照<对列表进行排序运算符就像默认的排序方法一样。你为什么不定义<您的员工类的操作员?

http ://www.cplusplus.com/reference/stl/list/sort/
Here is a page on the sort function for a list. The sort method can take a custom comparitor for sorting the list, but why would you? You sort your list by the < operator just like the default sorting method does. Why don''t you just define the < operator for your Employee class?

http://www.cplusplus.com/reference/stl/list/sort/


我知道comperator需要args。


我不明白。比较器对他们有什么影响?无论如何,错误信息非常清楚 - 使用& CityHall :: EmployeeComp''来创建指向成员的指针。 -


I know the comperator takes to args.

I don''t get it. What does comparator takes to them? Anyway, the error message is quite clear - "use ''&CityHall::EmployeeComp'' to create a pointer to member." -
will
展开 | 选择 | Wrap | 行号


你的问题是你试图调用成员函数市政府。但是要调用成员函数,你需要有一个类的实例来调用它,并且没有办法将该实例传递给list :: sort。


有一个解决方案:


删除EmployeeComps对CityHall类型对象的依赖。这很容易使它成为一个静态成员函数,它不需要一个对象,并通过类CityHall :: EmployeeComp将它传递给list :: sort。另一种方法是将方法完全移出CityHall类,然后将其置于全局范围内,这可能不太好。
Your problem is that you have tried to call a member function of CityHall. However to call a member function you need to have an instance of the class to call it on and there is no way to pass that instance into list::sort.

There is a solution:

Remove EmployeeComps dependency on having an object of type CityHall. This is easy make it a static member function which do not require an object to all and pass it to list::sort through the class CityHall::EmployeeComp . An alternative is to move the method out of the CityHall class entirely but then that puts it into global scope which is probably not good.


这篇关于通过自定义comperator对STL列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆