排序

必备知识

  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\n",arr[i].number,arr[i].score);
        }       
    }
    return 0;
}

 

 

posted @ 2020-04-01 21:29  天凉好个秋秋  阅读(118)  评论(0编辑  收藏  举报