sort函数

sort函数

一.sort函数有三个参数

void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);

1.第一个参数为排序数组的起始地址
2.第二个参数为排序数组的末地址的下一个地址
3.第三个参数为排序的方法,默认是升序排列,可以根据自己需要自定义排序方式(如降序排序,结构体排序)

二.数组排序实例:

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp1(int a,int b) {
	return a>b;//实现降序排列,也就是前面的大于后面的,用 > 号 
}
bool cmp2(int a,int b) {
	return a<b;//升序 
}
int main() {
	int a[10]= {45,12,34,77,90,11,2,4,5,55};
	sort(a,a+10,cmp1);//sort(a,a+10,greater<int>)也可以实现降序 
	//sort(a,a+10)或者sort(a,a+10,cmp2)实现升序 
	for(int i=0; i<10; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}

3.结构体排序

在这里插入图片描述

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <bits/stdc++.h>
#define ll long long
using namespace std;
typedef struct {//定义结构体 
	char name[100];
	int score;
} stu;
bool cmp(stu &a,stu &b) {//返回bool值 
	if(a.score!=b.score)//按分数排名 
		return a.score>b.score;
	else//如果分数一样,按名字从小到大排序 
		return strcmp(a.name,b.name)<0;
}
int main() {
	int N;
	cin>>N;
	stu a[N];
	for(int i=0; i<N; i++)
		cin>>a[i].name>>a[i].score;
	sort(a,a+N,cmp);
	for(int i=0; i<N; i++)
		cout<<a[i].name<<endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值