zoukankan      html  css  js  c++  java
  • C++标准库函数之用于排序的sort函数

    排序和查找可以说是计算机领域最经典的问题了,
    而C++标准库在头文件 algorithm 中已经内置了基于快速排序的函数sort,只需调用这个函数,就可以轻易地完成排序。

    下面简要介绍sort函数:sort ( first, last, comp )函数有三个参数:

      1. first:待排序序列的起始地址
      2. last:待排序序列的最后一个元素的下一地址,排序区间为[first, last)
      3. comp:排序方式,可以不填写,不填写时默认为升序方式

    当然sort函数支持多种数据类型,除了int以外,比如char,double,字符串等,都可以。

    例1:默认升序排序

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        int arr[5] = {3, 6, 1, 4, 7}; 
        cout << "排序前:";
        for (int i = 0; i < 5; i++) {
            cout << arr[i] << ' ';
        }
        cout << endl;
        sort(arr, arr + 5);                // 排序:默认升序
        cout << "排序后:";
        for (int i = 0; i < 5; i++) {
            cout << arr[i] << ' ';
        }
        return 0; 
    }
    输出结果:
    排序前:3 6 1 4 7
    排序后:1 3 4 6 7

    例2:降序排序,自己编写一个排序方式

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    bool Compare (int x, int y)                // 降序排序 
    {
        return x > y;
    }
    
    int main()
    {
        int arr[5] = {3, 6, 1, 4, 7}; 
        cout << "排序前:";
        for (int i = 0; i < 5; i++) {
            cout << arr[i] << ' ';
        }
        cout << endl;
        sort(arr, arr + 5, Compare);        // 排序 : 使用降序排序方式 
        cout << "排序后:";
        for (int i = 0; i < 5; i++) {
            cout << arr[i] << ' ';
        }
        return 0; 
    }
    输出结果:
    排序前:3 6 1 4 7
    排序后:7 6 4 3 1

    例3:通过自己定义排序方式,可以实现许多场景的排序
    比如:对学生成绩进行排序,按照从高到低进行排序,并将学生信息打印。学生信息包括学号,成绩;如果学生成绩相同,那么按学号的大小从小到大排序。

    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    struct Student {
        int number;            // 学号 
        int score;             // 成绩 
    };
    
    const int MAXN = 100;
    
    Student arr[MAXN];
    
    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;
        cin >> n;
        for (int i = 0; i < n; i++) {
            cin >> arr[i].number >> arr[i].score;
        }
        sort(arr, arr + n, Compare);
        cout << endl;
        for (int i = 0; i < n; i++) {
            cout << arr[i].number << ' ' << arr[i].score << endl;
        }
        return 0;
    }
    测试:
    4
    1 98
    2 90
    3 98
    4 89
    
    1 98
    3 98
    2 90
    4 89
  • 相关阅读:
    linux性能查看调优
    免密登录
    nginx配置
    Samba
    硬RAID与软RAID的区别
    LVM-扩容目录
    解决表面磁盘满,而实际没有大文件的问题
    LINUX下的JENKINS+TOMCAT+MAVEN+GIT+SHELL环境的搭建使用(JENKINS自动化部署)
    Docker 容器使用
    docker基础
  • 原文地址:https://www.cnblogs.com/MK-XIAOYU/p/12523226.html
Copyright © 2011-2022 走看看