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;
    }

     

  • 相关阅读:
    Linux下CVS的配置
    MSVC中的"pseudo register"调试技术
    flash cs4专业版下载(有注册码)
    Away3d学习笔记 away3d类库下载
    Away3D实例教程 贴图(EnviroBitmapMaterial)
    Away3D实例教程 贴图(Dot3BitmapMaterial)
    Away3D学习笔记1 戏说Flash 三维引擎
    Away3d基础6 – 位图材质
    away3D基础6颜色材质
    Away3d实例教程 贴图(texture mapping)
  • 原文地址:https://www.cnblogs.com/juanzhi/p/12616003.html
Copyright © 2011-2022 走看看