开学后的狂欢-----C++中的sort函数

根据胡凡和曾磊老师的《算法笔记》学习记录
说实话,我真是第一次才知道c++还有这么简便的排序函数,相比于C语言,省去了大量代码。

sort( )
使用方法:

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

举个栗子:

#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型数组

#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来自定义排序方式。

#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型数组

#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;
}

结构体数组排序

#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;
}
#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;
 } 

简单记录,庆祝开学…

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

敲代码的xiaolang

你的鼓励是我最大的动力

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

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

打赏作者

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

抵扣说明:

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

余额充值