1、ASCII码排序(sort()函数)

https://acm.hdu.edu.cn/showproblem.php?pid=2000

#include<iostream>
#include<algorithm>
using namespace std;
char a[3];
int main()
{   
	while(scanf(" %c%c%c",&a[0],&a[1],&a[2])!=EOF)
	{
		sort(a,a+3);
		cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
	}
	return 0;
 } 

运行结果:

相关知识点:

sort()函数

头文件 #include<algorithm>

void sort (first, last, Compare comp);
(1)第一个参数first:是要排序的数组的起始地址。
(2)第二个参数last:是结束的地址(最后一个数据的后一个数据的地址)
(3)第三个参数comp是排序的方法:可以是从升序也可是降序。
    如果第三个参数不写,则默认的排序方法是从小到大排序。写第三个参数,要写该参数对应的函数。例:
1、
 #include<iostream>
 #include<algorithm>
 using namespace std;
 bool cmp(int a,int b);
 int main(){
   //sort函数第三个参数自己定义,实现从大到小 
   int a[]={45,12,34,77,90,11,2,4,5,55};
   sort(a,a+10,cmp);
   for(int i=0;i<10;i++)
    cout<<a[i]<<" ";     
}
 //自定义函数
 bool cmp(int a,int b){
  return a>b;
} 

2、
  #include<iostream>
  #include<algorithm>
  #include"cstring"
 using namespace std;
  typedef struct student{
    char name[20];
    int math;
    int english;
 }Student;
 bool cmp(Student a,Student b);
 int main(){
   //先按math从小到大排序,math相等,按english从大到小排序 
   Student a[4]={{"apple",67,89},{"limei",90,56},{"apple",90,99}};
   sort(a,a+3,cmp);
   for(int i=0;i<3;i++)    
   cout<<a[i].name <<" "<<a[i].math <<" "<<a[i].english <<endl;     
 }
 bool cmp(Student a,Student b){
   if(a.math >b.math )
   return a.math <b.math ;//按math从小到大排序 
   else if(a.math ==b.math )
       return a.english>b.english ; //math相等,按endlish从大到小排序23 
 }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值