结构体排序

结构体排序,这里提供三种方法:

1.直接重写排序规则

struct Hero
{
    string name;
    int age;
    string sex;
};
​
int mtCompare(Hero a,Hero b) {
    return a.age < b.age;
}
int main()
{   
    Hero h[] = {
        {"刘备",23,"男"},
        {"关羽",22,"男"},
        {"张飞",20,"男"},
        {"赵云",21,"男"},
        {"貂蝉",19,"女"}
    };
    sort(h,h+5,mtCompare);
    for (int i = 0; i < 5; i++)
    {
        cout << "姓名:" << h[i].name << " 性别:" << h[i].age << " 年龄:" << h[i].age << endl;
    }
    system("pause");

2.bool operator型写法

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

2.1 在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

2.2 在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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值