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;
}