C++sort()对结构体类型排序

本文详细介绍如何使用C++对自定义结构体进行排序,包括使用比较函数和重载小于运算符两种方法,以及在结构体内和结构体外实现的不同方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

struct类型排序

#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
struct Date
{
    int a;
    int b;
};
bool com(const Date x,const Date y)
{
    if(x.a==y.a)
        return x.b>y.b;
    return x.a>y.a;
}
int main()
{
    Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}};
    sort(dat,dat+5,com); //按照第1个数由大到小排序,当第1个数相同时,按照第2个数由大到小排序
    for(int i=0;i<5;i++)
    {
        cout<<dat[i].a<<" "<<dat[i].b<<endl;
    }
    return 0;
}

输出:
5 6
3 8
3 7
2 9
1 10

bool operator型写法

operator重载小于运算符,可以设定由小到大排序,也可以设定由大到小排序
两种写法,可以写在struct内,也可以写在struct外。
这种写法区分于那种重载()运算符写法。

在struct外重载小于运算符

#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
struct Date
{
    int a;
    int b;
    
};
bool operator<(const Date &x,const Date &y)
{
    if(x.a == y.a)
        return x.b>y.b;
    return x.a>y.a;
}
int main()
{
    Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}};
    sort(dat,dat+5);
    for(int i=0;i<5;i++)
    {
        cout<<dat[i].a<<" "<<dat[i].b<<endl;
    }
    return 0;
}
输出:
5 6
3 8
3 7
2 9
1 10

在struct内重载小于运算符

#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
struct Date
{
    int a;
    int b;
    bool operator < (const Date &y) const
    {
        return b>y.b; //设定按照b由大到小排列
    }
};
int main()
{
    Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}};
    sort(dat,dat+5);
    for(int i=0;i<5;i++)
    {
        cout<<dat[i].a<<" "<<dat[i].b<<endl;
    }
    return 0;
}
输出:
1 10
2 9
3 8
3 7
5 6
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值