c++中sort基础用法

  • 用法一:数组排序

           对一个数组进行升序排序

#include <algorithm>
#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int a[100]={8,9,10,6,5,4};
    sort(a,a+6);
    for(int i=0;i<6;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

sort包含在#include<algorithm>中,sort(数组头,数组尾),sort(a,a+6)可以看作sort(a+0,a+6)表示对数组a的第0个元素到第5个元素进行排序。默认排序方式为升序排序。

如果想进行降序排序则需要引入自定义排序规则compare

#include <algorithm>
#include <iostream>
#include <cstdio>

using namespace std;
bool compare(int a,int b){
    return a>b;
}
int main()
{
    int a[100]={8,9,10,6,5,4};
    sort(a,a+6,compare);
    for(int i=0;i<6;i++){
        printf("%d ",a[i]);
    }
    return 0;
}

  • 用法2:结构体排序

有时我们会遇到这样的问题,按学生成绩进行降序排序,如果成绩相同按学号升序排序,怎么用sort解决这个问题呢?

​
struct student{
    int num;            //学号
    int score;          //成绩
};

bool cmp(student a,student b){//按成绩降序,再按学号升序
    if(a.score>b.score)return a.num<b.num;
    return a.score>b.score;
}

struct student stu[10];
//输入学生数据
sort(a,a+10,cmp);

​
  • 用法3:动态数组vector内的排序
vector<int>s;
sort(s.begin(),s.end());

注意事项:sort内集成了多种算法,时间复杂度会比n*n小但并不是nlogn

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值