STL--自定义类型的排序

STL的排序太坑了,尤其是在VS2010上重载sort函数的第三个比较参数的时候。

invalid operator <

这个错在写多关键字排序的时候就没有停止过。

本来想查书解决,结果各种重载都试了还是不行,百度才知道是因为:strict weak ordering。也就是说,如果a==b,则返回的应该是false,如果返回的是true,则会出上面的错。

参考这个:(http://hi.baidu.com/haochaoqing/item/00b40cf2b8c4efc0a835a255

所以最简单的这种比较函数:无论相等或者不等都返回1的写法

 1 bool comp(Student s1, Student s2){
 2     if(s1.score==s2.score)
 3         return 1;
 4     else
 5         return s1.id<s2.id;
 6 }   
 7 
 8 bool comp(Student s1, Student s2){
 9     if(s1.score!=s2.score)
10         return 1;
11     else
12         return s1.id<s2.id;
13 }    

这两种写法都会报错。

而无论相等或者不等都返回0的写法不会报错

 1 bool comp(Student s1, Student s2){
 2     if(s1.score==s2.score)
 3         return 0;
 4     else
 5         return s1.id<s2.id;
 6 }    
 7 bool comp(Student s1, Student s2){
 8     if(s1.score!=s2.score)
 9         return 0;
10     else
11         return s1.id<s2.id;
12 }    

故多关键字的STL排序可以写成:

 1 #include<time.h>
 2 #include<iostream>
 3 #include<vector>
 4 #include<algorithm>
 5 using namespace std;
 6 struct Node
 7 {
 8      int x;
 9      int y;
10 
11 };
12 bool Comp(Node &a,Node &b)
13 {
14     if(a.x==b.x) return b.y>a.y; 
15     else 
16         return a.x>b.x;
17 }
18 vector<Node> node;
19 int main()
20 {
21     srand((unsigned int)time(0));
22     for(int i=0;i<10;i++)
23     {
24         Node a;
25         a.x=rand()%(10+1-0)+0;
26         a.y=rand()%(10+1-0)+0;
27         node.push_back(a);
28     }
29     sort(node.begin(),node.end(),Comp);
30     for(int i=0;i<10;i++)
31     {
32         printf("%d %d
",node[i].x,node[i].y);
33     }
34 }
多关键字sort排序
原文地址:https://www.cnblogs.com/holyprince/p/3315051.html