如何对列表进行排序

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

嗨. 我们有一个班级的名单. 如何通过X作为变量对它进行排序?(X是Class的成员)

Hi. we have a list of one class. how to sort it by a variable as X ?( X is member of Class)

推荐答案

A)是否需要编写排序算法来对类成员变量? 或 B)您是否想知道如何使用类成员变量对STL中的类进行排序? 无论哪种情况,我都建议写一个函子来帮助您对类成员进行比较: A) Do you need to write a sorting algorithm to do the sorting on the class member variable? OR B) Do you want to know how to sort the class in STL with a class member variable? For either case, I would recommend writing a functor to help with the comparisons on your class member: struct CompareYourClassMemberXLess { bool operator()(const YourClass &lhs, const YourClass &rhs) { // If they reference the same object, return false. // This will create a strict weak ordering. if (&lhs == &rhs) return false; return lhs.GetX() < rhs.GetX(); } }; // The declaration for the call to "GetX() const" will need to be declared with const.

在排序之前,请创建函子的实例:

Create an instance of your functor before you sort:

CompareYourClassMemberXLess CmpXLess;

现在,在排序算法中,当您要比较两个值时,可以像调用函数一样调用变量CmpXLess来确定其在搜索顺序中的位置.

Now in your sort algorithm, when you want to compare the two values in, you can call the varible CmpXLess like a function to determine where it fits in the search order.

YourClass a; YourClass b; CmpXLess(a,b);

对于STL,请像这样使用它:

for STL use it like this:

std::sort(a.begin(), b.begin(), CompareYourClassMemberXLess());

顺便说一句,随意将令人讨厌的长名称更改为您的程序中有意义的名称.名称不会更改功能.

BTW, feel free to change the obnoxiously long names to something that makes sense in your program. The names will not change the functionality.

尝试使用此方法肯定会对您有所帮助... www.dotnetperls/sort-list [ ^ ] Try this will definitely help you... www.dotnetperls/sort-list[^]

请参阅: msdn.microsoft/en-us/library/b0zbh7b6.aspx#Y0 [^ ] msdn.microsoft/en -us/library/system.collections.arraylist.sort(v = vs.71).aspx [ ^ ] www.cplusplus/reference/stl/list/sort/ [ ^ ] 它会为您提供帮助. :) -MKB See : msdn.microsoft/en-us/library/b0zbh7b6.aspx#Y0[^] msdn.microsoft/en-us/library/system.collections.arraylist.sort(v=vs.71).aspx[^] www.cplusplus/reference/stl/list/sort/[^] It will help you. :) -MKB

更多推荐

如何对列表进行排序

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

发布评论

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

>www.elefans.com

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