排序规则下greater()和less()用法

greater()和less() 基于头文件(#include)

用sort举例 sort排序
升序 sort(arr,arr+len,less<>(type));
降序 sort(arr,arr+len,greater<>(type));

sort对结构体排序

先说用自定义函数的方法
代码

#include<iostream>  
#include<algorithm>//因为用了sort()函数  
#include<functional>//因为用了greater<int>()  
using namespace std;  
  struct node{
  	int num;
  	string name;
  }a[4];
  bool cmp(node x,node y){//node 类型 
  	return x.num>y.num;//降序排列 
  }
  
  
 int main()  
{  
 a[0].num=1;
 a[1].num=9;
 a[2].num=6;
 a[3].num=5;
 sort(a,a+4,cmp);
for(int i=0;i<4;i++){
	cout<<a[i].num<<" ";
} 
 return 0;
}  

先说自定义函数的方法
代码

#include<iostream>  
#include<algorithm>//因为用了sort()函数  
#include<functional>//因为用了greater<int>()  
using namespace std;  
  struct node{
  	int num;
  	string name;
  }a[4];
  bool cmp(node x,node y){//node 类型 
  	return x.num>y.num;//降序排列 
  }
  
  
 int main()  
{  
 a[0].num=1;
 a[1].num=9;
 a[2].num=6;
 a[3].num=5;
 sort(a,a+4,cmp);
for(int i=0;i<4;i++){
	cout<<a[i].num<<" ";
} 
 return 0;
}  

对8起 对结构体排序不会放下代码以后研究


#include <queue>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct Mi{
    int p;
    int h;
    int c;
    double k;
    Mi(int p,int h,int c,int k):p(p),h(h),c(c),k(k){}
    bool operator < (const Mi &a)const //对应less,代表升序,改变下行符号方向反之
    {  
        return p < a.p;
    }
    bool operator > (const Mi &a)const  //对应greater,代表降序、、、改变下行符号方向反之
    {  
        return p > a.p;
    }
};
bool cmp(const Mi &a,const Mi &b){
    return a < b;//<代表升序,>代表降序
}
int main(){
        vector<Mi> vec;
        int m;
        scanf("%d",&m);
        for(int i = 0;i < m;i++){
            int p,h,c;
            scanf("%d%d%d",&p,&h,&c);
            vec.push_back(Mi(p,h,c,1.0*p/h));
        }
        //sort(vec.begin(),vec.end());//升序排序  
        //sort(vec.begin(),vec.end(),cmp);//升序排序  
        //sort(vec.begin(),vec.end(),less<Mi>());//升序排序  
        sort(vec.begin(),vec.end(),greater<Mi>());//降序排序  
        int wei = 0;;
        for(vector<Mi>::iterator it = vec.begin();it!=vec.end();it++){
            cout <<it->p << " " << it->h << " " << it->c << " " << endl;
        }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值