学习笔记——sort排序

1.数组排序

sort排序的基本结构:sort(数组名,数组名+数组长度)

头文件:#include<algorithm>

sort排序初始是作为升序排列(小的在前,大的在后)

如果将sort变成降序排列(大的在前,小的在后)

则需自重定义一个cmp函数

1
2
3
4
bool cmp(int a,int b)
{
    return a>b;
}

或者:

1
2
3
4
5
bool cmp(int a,int b)
{
    if(a>b) return 1;
    else return 0;
}

2.结构体数组排序

当我们需要对结构体数组中某个变量进行排序时,我们必须要自定义一个cmp函数

如:

1
2
3
4
5
6
7
8
9
struct p{
    int num;
    string s;
}a[5];
bool cmp(p x,p y)
{
    if(x.num<y.num)  return 1;
    else  return 0;
}

将a数组按num变量从小到大排列

当然,也可以让结构体中别的变量加入排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
struct per{
    int num;
    int exa;
};
bool cmp(per x,per y)
{
    if(x.exa>y.exa)<br>     {
        return 1;
    }
    else
    {
        if(x.exa==y.exa)
        {
            if(x.num<y.num)
            {
                return 1;
            }
            else
            {
                return 0;
            }
             }
        else
        {
            return 0;
        }
    }
}//P1068

 上面代码的意思是,先比较x与y的exa,并让exa较大的在前,若相等,则比较x与y的num,并让num较小的在前.

补充:

若在第一个变量中,填上数组名+n,则sort只会排n后面的

如:

1
2
int a[5]={5,2,3,3,2};
sort(a+1,a+5);

排序后变成5,2,2,3,3


__EOF__

本文作者maysoul
本文链接https://www.cnblogs.com/maysoul/p/16053162.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   美索maysoul  阅读(253)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示