STL--自定义类型的排序

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

invalid operator <

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

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

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

bool comp(Student s1, Student s2){
    if(s1.score==s2.score)
        return 1;
    else
        return s1.id<s2.id;
}   

bool comp(Student s1, Student s2){
    if(s1.score!=s2.score)
        return 1;
    else
        return s1.id<s2.id;
}

 

这两种写法都会报错。

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

bool comp(Student s1, Student s2){
    if(s1.score==s2.score)
        return 0;
    else
        return s1.id<s2.id;
}    
bool comp(Student s1, Student s2){
    if(s1.score!=s2.score)
        return 0;
    else
        return s1.id<s2.id;
}

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

#include<time.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Node
{
     int x;
     int y;

};
bool Comp(Node &a,Node &b)
{
    if(a.x==b.x) return b.y>a.y; 
    else 
        return a.x>b.x;
}
vector<Node> node;
int main()
{
    srand((unsigned int)time(0));
    for(int i=0;i<10;i++)
    {
        Node a;
        a.x=rand()%(10+1-0)+0;
        a.y=rand()%(10+1-0)+0;
        node.push_back(a);
    }
    sort(node.begin(),node.end(),Comp);
    for(int i=0;i<10;i++)
    {
        printf("%d %d
",node[i].x,node[i].y);
    }
}

  ---上面是标准的写法...

 

原文地址:https://www.cnblogs.com/porter/p/3593856.html