0
点赞
收藏
分享

微信扫一扫

sort()函数——STL库


使用sort()函数,加上头文件#include<algorithm>、uisng namespace std;

使用格式:

sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(选填))

⚠️:不写比较函数,默认进行递增进行排序。

示例代码:

#include<cstdio>
#include<algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
int A[] = {5, 4, 3, 2, 1};
sort(A, A + 3);
for (int i = 0; i < 5; ++i)
{
printf("%d ",A[i]);
}
printf("\n");

sort(A,A + 5);
for (int i = 0; i < 5; ++i)
{
printf("%d ",A[i]);
}
printf("\n");
return 0;
}

示例代码2:(double数据)

#include<cstdio>
#include<algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
double A[3] ={2.4, -3.1, 1.7};
sort(A,A + 3);
for (int i = 0; i < 3; ++i)
{
printf("%.1f ",A[i] );
}
printf("\n");
return 0;
}

示例代码3:(char数据)【默认字典序】

#include<cstdio>
#include<algorithm>
using namespace std;
int main(int argc, char const *argv[])
{
char str[] ={'K', 'J', 'A', 'Z'};
sort(str, str + 4);
for (int i = 0; i < 4; ++i)
{
printf("%c ",str[i] );
}
printf("\n");
return 0;
}

比较函数的实现:

1、基本数据类型

#include<cstdio>
#include<algorithm>
using namespace std;

bool cmp(int a, int b){
return a > b;
}
int main(int argc, char const *argv[])
{
int A[] = {2, 5, 1, 3, 4};
sort(A, A + 5, cmp);

for (int i = 0; i < 5; ++i)
{
printf("%d ",A[i]);
}
printf("\n");
return 0;
}


#include<cstdio>
#include<algorithm>
using namespace std;

bool cmp(double a, double b){
return a > b;
}
int main(int argc, char const *argv[])
{
double A[3] ={2.4, -3.1, 1.7};
sort(A,A + 3, cmp);
for (int i = 0; i < 3; ++i)
{
printf("%.1f ",A[i] );
}
printf("\n");
return 0;
}
#include<cstdio>
#include<algorithm>
using namespace std;

bool cmp(char a, char b){
return a > b;
}
int main(int argc, char const *argv[])
{
char str[] ={'K', 'J', 'A', 'Z'};
sort(str, str + 4, cmp);
for (int i = 0; i < 4; ++i)
{
printf("%c ",str[i] );
}
printf("\n");
return 0;
}

2、结构体数组排序

#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
int x,y;
}ssd[10];

bool cmp(node a, node b){
if(a.x != b.x) return a.x > b.x;
else return a.y < b.y;
}
int main(int argc, char const *argv[])
{
ssd[0].x = 2;
ssd[0].y = 2;
ssd[1].x = 1;
ssd[1].y = 3;
ssd[2].x = 2;
ssd[2].y = 1;

sort(ssd, ssd + 3, cmp);

for (int i = 0; i < 3; ++i)
{
printf("%d %d\n", ssd[i].x, ssd[i].y);
}
return 0;
}

3,容器的排序

⚠️:只有vector、string、deque是可以使用sort的,因为像set、map这种容器(用红黑树实现的)元素本身就是有序的。



举报

相关推荐

0 条评论