C++标准库函数之用于排序的sort函数

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

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

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

例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

猜你喜欢

转载自www.cnblogs.com/MK-XIAOYU/p/12523226.html