如何对列表进行排序 [英] how to sort the list
本文介绍了如何对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨.
我们有一个班级的名单.
如何通过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.
尝试使用此方法肯定会对您有所帮助...
http://www.dotnetperls.com/sort-list [
Try this will definitely help you...
http://www.dotnetperls.com/sort-list[^]
请参阅:
http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx#Y0 [^ ]
http://msdn.microsoft.com/en -us/library/system.collections.arraylist.sort(v = vs.71).aspx [ http://www.cplusplus.com/reference/stl/list/sort/ [ ^ ]
它会为您提供帮助. :)
-MKB
See :
http://msdn.microsoft.com/en-us/library/b0zbh7b6.aspx#Y0[^]
http://msdn.microsoft.com/en-us/library/system.collections.arraylist.sort(v=vs.71).aspx[^]
http://www.cplusplus.com/reference/stl/list/sort/[^]
It will help you. :)
-MKB
这篇关于如何对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文