服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - 带你了解C++中的sort函数

带你了解C++中的sort函数

2021-12-24 14:37敲代码的xiaolang C/C++

这篇文章主要给大家介绍了关于C++中sort函数的基础入门使用的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用C++具有一定的参考学习价值,需要的朋友们下面来一起看看吧

sort( )

使用方法:

sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填))
必须加上头文件:#include< algorithm >和using namespace std;

举个栗子:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
    int book[5]={5, 4, 2, 8, 7};
    sort(book,book+5);
    int i;
    for(i=0;i<5;i++)
    {
        printf("%d ",book[i]);
    }
    return 0;
}

char型数组

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h>
#include<algorithm>
using namespace std;
int main()
{
    char book[]={'A','L','B','Q'};
    sort(book,book+4);
    int i;
    for(i=0;i<4;i++)
    {
        printf("%c ",book[i]);
    }
    return 0;
}

我们上面的排序都是由小到大排序,然后我们可以使用cmp来自定义排序方式。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
    return a>b;//a大于b时,把a放在前面
}
int main()
{
    int book[ ]={5,2,0,1,3,1,4};
    sort(book,book+7,cmp);
    int i;
    for(i=0;i<7;i++)
    {
        printf("%d ",book[i]);
    }
    return 0;
}

char型数组

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(char a,char b)
{
    return a>b;
}
int main()
{
    char book[]={'Q','S','A','Z','L'};
    sort(book,book+5,cmp);
    int i;
    for(i=0;i<5;i++)
    {
        printf("%c ",book[i]);
    }
    return 0;
}

结构体数组排序

?
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
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
    int x,y;   
}book[10];
bool cmp(node a,node b)
{
    return a.x>b.x;//按x由大到小排序
}
int main()
{
    book[0].x=5;
    book[0].y=2;
    book[1].x=0;
    book[1].y=5;
    book[2].x=2;
    book[2].y=1;
    sort (book,book+3,cmp);
    int i;
    for(i=0;i<3;i++)
    {
        printf("%d %d \n",book[i].x,book[i].y);
    }
    return 0;
}
?
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
29
#include<stdio.h>
#include<algorithm>
using namespace std;
struct node
{
    int x,y;   
}book[10];
bool cmp(node a,node b)
{
    if(a.x!=b.x)
    return a.x>b.x;//x不等时按x排序
    else return a.y<b.y;//x相等时按y排序
}
int main()
{
    book[0].x=5;
    book[0].y=2;
    book[1].x=0;
    book[1].y=5;
    book[2].x=2;
    book[2].y=1;
    sort (book,book+3,cmp);
    int i;
    for(i=0;i<3;i++)
    {
        printf("%d %d \n",book[i].x,book[i].y);
    }
    return 0;
 }

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注服务器之家的更多内容!

原文链接:https://blog.csdn.net/weixin_52605156/article/details/119988008

延伸 · 阅读

精彩推荐