排序自定义类型的列表

编程入门 行业动态 更新时间:2024-10-11 05:25:04
本文介绍了排序自定义类型的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想要一个stl 列表的对象,其中每个对象包含两个 int 的。 之后,我想使用stl :: sort在第一个 int 的值后对列表排序。 如何告诉排序函数,它应该排序在第一个 int ?

I want to have a stl list of objects where each object contains two int's. Afterwards I want to sort the list with stl::sort after the value of the first int. How do I tell the sort function that it's supposed to sort after the first int?

推荐答案

您可以指定自定义排序谓词。在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.

更多推荐

排序自定义类型的列表

本文发布于:2023-11-28 07:54:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641559.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   类型   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!