结构体sort排序

结构体sort排序

sort函数包含在头文件为 #include < algorithm > 中。

sort (first, last, cmp)

(1) first:是要排序的数组的起始地址。

(2) last:是结束的地址(最后一个数据的后一个数据的地址)

(3) cmp:排序方法,可以是从升序也可是降序。如果不写,则默认从小到大排序。

// 1.采用默认从小到大排序
int a[9] = {9,8,7,6,5,4,3,2,1};
sort(a, a+9);
for(int i = 0; i <= 8; i++) cout << a[i] << ' ';

// 2.自定义函数 从大到小排序 
bool cmp(int a, int b){
  return a>b;
}
sort(a, a+10, cmp); 
  
// 3.结构体排序
struct node{
	int x, y;
}a[n];
bool cmp(node a, node b){
	if(a.x!=b.x) return a.x<b.x;
	else return a.y<b.y; //若第一项相等则比较第二项
}
sort(a, a+n, cmp);
e.g.
67 89
90 56
90 99


例题:P1223 排队接水

P1223 排队接水
P1223 排队接水

#include<bits/stdc++.h>
const int N=1005;
using namespace std;
struct node{
	int x;
	int y;
}a[N];
bool cmp(node x,node y){
	if(x.x!=y.x) return x.x<y.x;
	else return x.y<y.y;
}
int main(){
	int n;
	cin>>n;
	double sum=0;
	for(int i=1;i<=n;i++){
		int k;
		cin>>k;
		a[i].x=k;
		a[i].y=i;
	}
	sort(a+1,a+1+n,cmp);
	for(int i=1;i<=n;i++)
	{
		printf("%d ",a[i].y);
		sum+=a[i].x*(n-i);
	}
	cout<<endl;
	printf("%.2f",1.0*sum/n);
	return 0;
} 
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值