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这种容器(用红黑树实现的)元素本身就是有序的。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

繁星蓝雨

如果觉得文章不错,可以请喝咖啡

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值