C++ sort排序函数用法及实例

一、头文件
#include < algorithm >
二、具体用法
1、sort函数的参数:sort(start,end,cmp)。
1)start表示待排序数组的开始地址。
2)end表示结束的地址;
3)cmp代表排序的方法,可以是升序也可以是降序,不加cmp参数是默认是升序。
三、实例
1)不带cmp参数,默认升序排序

#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
    int arr[]={9,5,3,2,10,2};
    for(int i=0;i<6;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    sort(arr,arr+6);
    for(int i=0;i<6;i++)
        cout<<arr[i]<<" ";
    cout<<endl;

}
9 5 3 2 10 2
2 2 3 5 9 10

2)降序排序,通过cmp参数实现具体的方法

#include <iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
    if(a!=b)
        return a>b;
}
int main()
{
    int arr[]={9,5,3,2,10,2};
    for(int i=0;i<6;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    sort(arr,arr+6,cmp);//直接写参数cmp名称即可,不用对cmp传参
    for(int i=0;i<6;i++)
        cout<<arr[i]<<" ";
    cout<<endl;

}
9 5 3 2 10 2
10 9 5 3 2 2

结构体数组也可用此方法进行排序

#include <iostream>
#include<algorithm>
using namespace std;
struct Key
{
    int num;
    int time;
};
bool cmp(Key x,Key y)
{
    if(x.num!=y.num)
        return x.num>y.num;//num降序排序
    if(x.time!=y.time)
        return x.time<y.time;//如果num相等按time升序排序
}
int main()
{
    Key arr[3];
    arr[0].num=1;
    arr[0].time=1;
    arr[1].num=2;
    arr[1].time=2;
    arr[2].num=3;
    arr[2].time=1;
    sort(arr,arr+3,cmp);
    for(int i=0;i<3;i++)
        cout<<arr[i].num<<" "<<arr[i].time<<endl;
}
num time
3 	1
2 	2
1 	1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值