对自定义类型的列表进行排序

2024-05-11C/C++开发问题
5

本文介绍了对自定义类型的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想要一个 stl list 对象,其中每个对象包含两个 int.之后我想在第一个 int 的值之后使用 stl::sort 对列表进行排序.我如何告诉排序函数它应该在第一个 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.)

最后,如果这有意义,您还可以为您的自定义类配备 operator<.这允许您在任何有序上下文中自由使用该类,但请务必了解其后果.

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.

这篇关于对自定义类型的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6