C++ ---sort函数的使用(包含和结构体的结合使用)

1. sort函数的使用

1.1 sort函数的一般使用

头文件:

#include <algorithm>

#include<iostream>
#include<algorithm>//加头文件
using namespace std;
//按照从大到小进行排序
bool cmp(const int &a,const int &b){
    return a>b;
}

int main(){
    int num[]={3,0,12,6,9,10,-5,8,7,22};
    //sort(num,num+10);
    //前五个数从小到大排序
    sort(num,num+5);//sort(开始位置,结束位置);默认从小到大排序
    //后五个数从大到小排序
    sort(num+5,num+10,cmp);
    for(int i = 0;i<10;i++){
        cout<<num[i]<<" ";
    }
    cout<<endl;
    return 0;
}

1.2 sort函数和结构体的组合

1.2.1 方法1:自定义比较函数

#include<iostream>
#include<algorithm>
using namespace std;

struct node{
    int x,y;
};

bool cmp_node(const node &a,const node &b){
    if(a.x == b.x){//如果x相同,按照y的值从大到小排序
        return a.y>b.y;
    }
    return a.x>b.x;//优先按照x的值从大到小排序
}

int main(){
    node t[10];
    t[0].x = 5,t[0].y = 1;
    t[1].x = 7,t[1].y = 0;
    t[2].x = 6,t[2].y = 9;
    t[3].x = 6,t[3].y = 22;
    t[4].x = 6,t[4].y = 15;
    sort(t,t+5,cmp_node);
    for(int i = 0;i<5;i++){
        cout<<t[i].x<<" "<<t[i].y<<endl;
    }
    return 0;
}

1.2.2 方法2:重载 <(小于)符号

#include<iostream>
#include<algorithm>
using namespace std;

struct node{
    int x,y;
    //重载操作符<
    bool operator< (const node &b) const{
        if(this->x == b.x)//如果x相同,按照y的值从大到小排序
            return this->y>b.y;
        return this->x>b.x;//优先按照x的值从大到小排序
    }
};

int main(){
    node t[10];
    t[0].x = 5,t[0].y = 1;
    t[1].x = 7,t[1].y = 0;
    t[2].x = 6,t[2].y = 9;
    t[3].x = 6,t[3].y = 22;
    t[4].x = 6,t[4].y = 15;
    sort(t,t+5);//写法不变
    for(int i = 0;i<5;i++){
        cout<<t[i].x<<" "<<t[i].y<<endl;
    }
    return 0;
}

总结:自定义比较函数时,切记不要使用>=或<=。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值