且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

排序自定义类型的列表

更新时间:2022-05-27 21:38:43

您可以指定自定义排序谓词。在C ++ 11中,***使用lambda:

You can specify a custom sort predicate. In C++11 this is best done with a lambda:

typedef std::pair<int, int> ipair;
std::list<ipair> thelist;

thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; });

在旧版本的C ++中,您必须编写一个适当的函数:

In older versions of C++ you have to write an appropriate function:

bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; }

thelist.sort(compFirst);

(如果 ipair 有你自己的数据结构;只需修改比较函数相应地访问相关的数据成员。)

(Instead if ipair you can of course have your own data structure; just modify the comparison function accordingly to access the relevant data member.)

最后,如果这是有道理的,你也可以装备你的自定义类运算符。这允许你在任何有序的上下文中***使用类,但一定要了解这种情况的后果。

Finally, if this makes sense, you can also equip your custom class with an operator<. That allows you to use the class freely in any ordered context, but be sure to understand the consequences of that.