c++ sort函数

这篇博客介绍了如何使用C++的sort函数对整型数组进行升序和降序排序,并展示了对包含字符串、整数和ID的结构体数组按不同字段进行排序的方法。示例代码中,通过自定义比较函数实现了结构体中数字和字符串的定制排序。
摘要由CSDN通过智能技术生成

首先是int类型排序

#include<bits/stdc++.h>
using namespace std;
bool cmp(int x,int y)
{
	return x<y;   //从小到达排序,
//	return x>y;	  //若改为x>y则为降序排 
}
int main()
{
	int n,i;
	scanf("%d",&n);
	int a[n];
	for(i=0;i<n;i++)
	scanf("%d",&a[i]);
	sort(a,a+n,cmp);
	for(i=0;i<n;i++)
	{
		printf("%d ",a[i]);
	}
 } 

这里用到的是万能头,也可以使用#include<algorithm>

sort()里面首先要填排序的数组及地址,然后是长度,最后是一个函数(若不写则默认为升序排列)。

下面的是结构体的排序:

#include<bits/stdc++.h>
using namespace std;
typedef struct data{
	string a;
	int score;
	string id;
}N;
bool cmp1(data x,data y)
{
	return x.score<y.score;
}
bool cmp2(data x,data y)
{
	return x.id<y.id;
}

int main()
{
	int n,i;
	cin>>n;
	N str[n];
	for(i=0;i<n;i++)
	{
		cin>>str[i].a>>str[i].score>>str[i].id;
	}
	cout<<endl;
	sort(str,str+n,cmp1);
	for(i=0;i<n;i++)
	cout<<str[i].a<<" "<<str[i].score<<"  "<<str[i].id<<endl;
	cout<<endl;
	sort(str,str+n,cmp2);
	for(i=0;i<n;i++)
	cout<<str[i].a<<" "<<str[i].score<<"  "<<str[i].id<<endl;
	
}

这里是对结构体的数字和ID(字符串)进行的排序

需要用c++中的string来定义字符串,如果用字符数组则无法对其进行比较。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值