sort函数

头文件
#include <algorithm>
使用方法

sort()函数可以对给定区间所有元素进行排序。它有三个参数sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,cmp参数可以不写,如果不写的话,默认从小到大进行排序。如果我们想从大到小排序可以将cmp参数写为greater<int>()就是对int数组进行排序,当然<>中我们也可以写double、long、float等等。

自定义排序准则

如果我们需要按照其他的排序准则,那么就需要我们自己定义一个bool类型的函数来传入。比如说假如要按照每个数的个位数进行从大到小排序,可以写一个bool函数:

bool cmp(int x,int y){
    return x % 10 > y % 10;//因为要排序的是两位数,就模10了
}

然后把这个函数当成参数传入sort()中

#include<iostream>
#include<algorithm>
using namespace std;
​
bool cmp(int x,int y){
    return x % 10 > y % 10;
}
​
int main(){
    int num[10] = {65,59,96,13,21,80,72,33,44,99};
    sort(num,num+10,cmp);
    for(int i=0;i<10;i++){
        cout<<num[i]<<" ";
    }//输出结果:59 99 96 65 44 13 33 72 21 80
    
    return 0;
    
} 
对结构体排序

定义一个结构体

struct Student{
    string name;
    int score;
    Student() {}
    Student(string n,int s):name(n),score(s) {}
};

按成绩高低进行排序

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
​
struct Student{
    string name;
    int score;
    Student() {}
    Student(string n,int s):name(n),score(s) {}
};
​
bool cmp_score(Student x,Student y){
    return x.score > y.score;
}
​
int main(){
    Student stu[3];
    string n;
    int s;
    for(int i=0;i<3;i++){
        cin>>n>>s;
        stu[i] = Student(n,s);
    }
    
    sort(stu,stu+3,cmp_score);
    
    for(int i=0;i<3;i++){
        cout<<stu[i].name<<" "<<stu[i].score<<endl;
    }
    
    return 0;
}

参考文献:C++ sort()排序详解-优快云博客,这篇写的更全面,我的这篇只是整理下来自己用,大家有需要可以去看原文。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值