sort 排序

sort排序:

sort 排序是C++的一种排序方法,已经包含在函数库里面,需要用的话,可以直接调用哦!默认从小到大排序,当然也可以自写函数,令其从大到小排序,简单方便,不像冒泡那样复杂,但是需要加上 #include <algorithm> 头文件,当然 C++ 基础的 #include <iostream> 头文件也不可少。

使用方法:

在程序顶部加上#include <algorithm> 头文件以后,用数组来存放需要排序的数据,然后当作一语句进行写入即可。
sort (数组名 + 初始位置,数组名 + 末尾位置 + 1,(函数));
初始位置如果是 0,可以不写的哦。

简要代码:

#include <iostream>
#include <algorithm> //sort排序所需的头文件
using namespace std;
bool cmp(int x, int y) //自写排序的函数
{
    return x > y;
}
int main()
{
    int a[100], m;
    cin >> m;
    for(int i = 0; i < m; i++)
        cin >> a[i];

    sort(a, a+m, cmp); //其实真正写进程序的,也就这一行哦

    for(int i = 0; i < m; i++)
        cout << a[i] << " " ;
    return 0;
}

sort排字符串:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int n;
    string a[100];
    cin >> n;
    for(int i = 0; i < n; i++)
        cin >> a[i];
    sort(a, a+n);   //一样的写法
    for(int i = 0 ; i < n; i++)
        cout << a[i] << endl;
    return 0;
}

注意:sort只能排标准的string字符串,字符数组是排不了的!!

sort排结构体:

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
struct student
{
    int id;
    int score;
}a[100];
bool cmp(student a, student b)
{
    if(a.score != b.score) //分数不同按分数
        return a.score > b.score;
    else                   //相同则按id
        return a.id < b.id;
}
int main()
{
    int n;
    cin >> n;
    for(int i = 0; i < n; i++)
        cin >> a[i].score >> a[i].id;
    sort(a, a+n, cmp);   //一样的写法
    for(int i = 0 ; i < n; i++)
        cout << a[i].score << " " << a[i].id << endl;
}

 

 

 

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值