zoukankan      html  css  js  c++  java
  • 排序

    必备知识

      1.排序用的函数 sort

      2. 引入头部文件 #include <alogrithm>

      3.自定义类型函数重写

      4.运算符重载

    案例一 整数奇数偶数排序

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    
    /**
    * 奇数在前,从大到小;偶数在后,从小到大 
    */ 
    using namespace std;
    
    bool Compare(int x,int y){
        //如果两个都是奇数
        if(x % 2 == 1 && y % 2 == 1){
            //从大到小 
            return x > y;
        }else if(x % 2 == 0 && y % 2 == 0){
            return x < y;
        }else if(x % 2 == 0 && y % 2 == 1){
            return false;
        }else{
            return true;
        }
    }
    
    int arr[10];
    
    int main(){
        int n;
        while(scanf("%d",&n)!=EOF){
            for(int i = 0;i < n;i++){
                scanf("%d",&arr[i]);
            }
            sort(arr,arr+n,Compare);
            for(int i = 0;i < n;i++){
                printf("%d ",arr[i]);
            }          
        }
        return 0;
    }

    案例二 学生成绩排序。按照分数排序,如果分数相同,按照学号排序

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    
    using namespace std;
    
    //学生结构体 
    struct Student{
        int number;
        int score;
        //运算符重载 
        bool operator<(Student student) const{
            if(score == student.score{
                return number < student.number;
            }else{
                return score < student.score;
            }
        }
    };
    
    Student arr[100];
    
    //bool Compare(Student x,Student y){
    //    if(x.score == y.score){
    //        return x.number < y.number;
    //    }else{
    //        return x.score < y.score; 
    //    }
    //}
    
    int main(){
        int n;
        while(scanf("%d",&n)!=EOF){
            for(int i = 0;i < n;i++){
                scanf("%d%d",&arr[i].number,&arr[i].score);
            }
    //      sort(arr,arr+n,Compare);
            sort(arr,arr+n);
            for(int i = 0;i < n;i++){
                printf("%d %d
    ",arr[i].number,arr[i].score);
            }       
        }
        return 0;
    }

     

  • 相关阅读:
    Android获取当前时间的3中方法总结
    解决 C# .NET WebClient WebRequest请求缓慢的问题
    无刷新的批量图片上传插件.NET版
    <img>标签显示本地路径的图片的.NET解决方案
    无刷新分页
    Shader基本类型
    shader内置变量和函数
    Shader基础
    Lua中的基本函数库
    Lua中的操作系统库
  • 原文地址:https://www.cnblogs.com/juanzhi/p/12616003.html
Copyright © 2011-2022 走看看