sort

1. 普通排序:升序
sort() 区间:[ , )

int a[10]={2,5,6,9,8,4,3,5,6,100};
sort(a,a+10); //2 3 4 5 5 6 6 8 9 100

可以对数组中任意一段排序

int a[10]={2,5,6,9,8,4,3,5,6,100};
sort(a+2,a+5);//2 5 6 8 9 4 3 5 6 100

2. 降序
(1)greater 参数

int a[10]={2,5,6,9,8,4,3,5,6,100};
sort(a,a+10,greater<int>()); //100 9 8 6 6 5 5 4 3 2
//greater< >() 尖括号里面的数据类型可以改 但是形式必须一样

(2)struct -bool 式 即自定义排序类型, 非常灵活,不仅可以写降序,想什么顺序就什么顺序。
形式如下:

struct *rule1*       //除了* *中的可变,其余部分照抄 a1,a2 不建议变更就是一个参数
{
 bool operator()(const *int* &*a1*,const *int* &*a2*) //int 可变更 ,是数据类型
 {
  *return a1>a2;*         //这一部分阐释按什么规则排序 现在这个就是按降序
 } 
};

3.结构体排序

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<map>
using namespace std;
struct student{
 int a;
 char b[50];
 double c;
} STU[]={{5,"asef",500},{6,"gdfg",10.5},{50,"rth",20.3},{30,"trh",10.8}};
struct rule1   //规则一:按结构体中的a的降序 排结构体数组
{
 bool operator()(const student &a1,const student &a2)
 {
  return a1.a>a2.a;
 } 
};
struct rule2{  //规则二:按结构体中的c的降序 排结构体数组
 bool operator()(const student &a1,const student &a2)
 {
  return a1.c>a2.c;
 };
};
struct rule3 //规则三:按结构体中的b的降序 排结构体数组
{
 bool operator() ( const student &a1,const student &a2)
 {
  if(stricmp(a1.b,a2.b)>0)   //stricmp()  比较两个字符串s1 s2,if(s1>s2) 返回>0
  			    //			             if(s1<s2) 返回<0
  			    //				     if(s1=s2) 返回=0
   return true;
  else
   return false;
 };
};
void PRINT(student STU[],int n)
{
 for(int i=0;i<4;i++)
 {
  printf("%d %s %lf    ",STU[i].a,STU[i].b,STU[i].c);
 }
 cout<<endl;
}
int main()
{
 
 sort(STU,STU+5,rule1()); PRINT(STU,1);
 sort(STU,STU+5,rule2()); PRINT(STU,1);
 sort(STU,STU+5,rule3()); PRINT(STU,1);
 return 0;
}
/*
4672992  0.000000    50 rth 20.300000    30 trh 10.800000    6 gdfg 10.500000
5 asef 500.000000    50 rth 20.300000    30 trh 10.800000    6 gdfg 10.500000
30 trh 10.800000    50 rth 20.300000    6 gdfg 10.500000    5 asef 500.000000
*
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值