C++中 sort() 的使用

版权声明:来自lucien.ink,转载请注明文章出处。 https://blog.csdn.net/xs18952904/article/details/81463822

博客地址

http://www.lucien.ink/archives/311/

摘要

需要头文件<algorithm>

函数名 功能描述
sort 对给定区间所有元素进行排序
stable_sort 对给定区间所有元素进行稳定排序
partial_sort 对给定区间所有元素部分排序
partial_sort_copy 对给定区间复制并排序
nth_element 找出给定区间的某个位置对应的元素
is_sorted 判断一个区间是否已经排好序
partition 使得符合某个条件的元素放在前面
stable_partition 相对稳定的使得符合某个条件的元素放在前面

语法描述

sort(begin, end, cmp),其中begin为指向待sort()的数组的第一个元素的指针,end为指向待sort()的数组的最后一个元素的下一个位置的指针,cmp参数为排序准则,如果没有的话,默认以非降序排序。

以int为例的基本数据类型的sort()使用

#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    int a[5] = {1, 3, 4, 2, 5};
    sort(a, a + 5);
    for (int i = 0; i < 5; i++) cout << a[i] << ' ';
    return 0;
}

输出结果为:1 2 3 4 5

自定义cmp参数

#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int x, int y) {
    return x > y;
}
int main() {
    int a[5] = {1, 3, 4, 2, 5};
    sort(a, a + 5, cmp);
    for (int i = 0; i < 5; i++) cout << a[i] << ' ';
    return 0;
}

输出结果为:5 4 3 2 1

猜你喜欢

转载自blog.csdn.net/xs18952904/article/details/81463822