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\n",node[i].x,node[i].y);
    }
}

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

 

 

 

转载于:https://www.cnblogs.com/porter/p/3593856.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值