• 对结构体进行排序


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

    有时候编程的时候需要针对结构体中的某一个变量进行排序,那么如何用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;
    }

    运行结果:

  • 相关阅读:
    校验器
    Mybatis分页中遇到的坑3

    Lock1
    Validation(4)-临时
    在Java中如何判断对象已死?
    垃圾回收算法的种类
    Java内存区域
    Java 中的 volatile关键字含义
    分别写出堆内存溢出与栈内存溢出的程序?
  • 原文地址:https://www.cnblogs.com/program-ai-cv-ml-se-fighting/p/11670142.html
Copyright © 2020-2023  润新知