#算法 sort 用法 & 结构体排序

sort(1,2,3)

1,2为地址,3可以省略,3是函数名。
1,2代表从1到2之间的变量进行排序。
3表示自定义排序方式。可以不填,默认从小到大。

3函数的写法

bool类型,两个参数,a,b。ab的类型为你排序的变量的类型。返回值为True,则第一个参数考前,为False则反之。

举个例子:一个从大到小的排序:

bool cmpare(int a,int b){
    return a>b;
}
int miaoh[max_n];


sort(miaoh,miaoh+n,compare);

结构体

再举个更大的例子:

#include<bits/stdc++.h>
using namespace std;
typedef struct node{
    string name;
    int score;
}node;
node student[max_n];
bool compare(node a1,node a2){
    return a1.score > a2.score;
}
int n,x;
string in;
int main(){
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> x >> in;
        student[i] = {in,x};
    }
    sort(student,student + n,compare);
    cout << student[0].name;
    return 0;
}