对结构体进行排序

第一篇博客,记录一下~给自己留一个学习笔记

有时候编程的时候需要针对结构体中的某一个变量进行排序,那么如何用sort函数来排序呢?

自己定义一个cmp函数即可,有升序和降序两种,代码如下:

#include<bits/stdc++.h>
using namespace std;
struct st{
    int x;
    int y;
};
//升序 
int cmp1(st i,st j){
    return i.y<j.y;
}
//降序 
int cmp2(st i,st j){
    return i.y>j.y;
}
int main(){
    st a[]={{1,2},{2,1}};
    cout<<"a[0].x="<<a[0].x<<" a[0].y="<<a[0].y<<" a[1].x="<<a[1].x<<" a[1].y="<<a[1].y<<endl; 
    sort(a,a+2,cmp1);//cmp作为第三个参数 
    cout<<"'y'的升序排列:a[0].x="<<a[0].x<<" a[0].y="<<a[0].y<<" a[1].x="<<a[1].x<<" a[1].y="<<a[1].y<<endl;     
    sort(a,a+2,cmp2);
    cout<<"'y'的降序排列:a[0].x="<<a[0].x<<" a[0].y="<<a[0].y<<" a[1].x="<<a[1].x<<" a[1].y="<<a[1].y<<endl; 
    
    return 0;
}

运行结果:

原文地址:https://www.cnblogs.com/program-ai-cv-ml-se-fighting/p/11670142.html