C++ sort排序

Posted on   yacbo  阅读(66)  评论(0编辑  收藏  举报

 

 

 

复制代码
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;
}
复制代码

 

相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
历史上的今天:
2019-02-27 Sql语句获取表头信息

随笔 - 186, 文章 - 0, 评论 - 4, 阅读 - 19万

Copyright © 2025 yacbo
Powered by .NET 9.0 on Kubernetes

点击右上角即可分享
微信分享提示