C++ sort排序

2022/2/27 20:22:50

本文主要是介绍C++ sort排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 

 

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


自定义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;
}

 



这篇关于C++ sort排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程