结构体+sort()第三参数为自定义函数名
eg1
比较函数内部逻辑的实现:第一参数在第二参数之前的情况写在return里!
比较函数经常是先考虑“等于”的情况 再考虑“大于小于”
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct student{
int num;
int grade;
};
int compare(student a,student b){//!!!
if(a.grade==b.grade){
return a.num<b.num;
}
return a.grade<b.grade;
}
int main(){
int n;
while(cin>>n){
vector<student> s(n);
for(int i=0;i<n;i++){
cin>>s[i].num>>s[i].grade;
}
sort(s.begin(),s.end(),compare);//3rd参数
for(int i=0;i<n;i++){
cout<<s[i].num<<" "<<s[i].grade<<endl;
}
}
}
eg2 还是:第一参数在第二参数之前的情况写在return里!
eg3 奥运排序
1.给【输入】的指定部分排序 :方法是把指定部分存入待排vector 并且在结构体struct中用order指出存入顺序
2.现有奖牌榜的四种排序方法,对于每一个国家输出最有利的排序方法和排名: 方法是分别用四种方法排序,结构体内f1~4分别记录四种方法下的位次。
3.【并列排名时,即如果出现金牌总数为 100,90,90,80.则排名为1,2,2,4】: 先正常排 再用while循环check和前面的大小 如果一样则排名降。
#include<cstdio>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct country{
int order;
int gold;
int total;
int popu;
int f1;
int f2;
int f3;
int f4;
};
int compare1(country x,country y){
return x.gold>y.gold;
}
int compare2(country x,country y){
return x.total>y.total;
}
int compare3(country x,country y){
float perx=(float)x.gold/x.popu;
float pery=(float)y.gold/y.popu;
return perx>pery;
}
int compare4(country x,country y){
float perx=(float)x.total/x.popu;
float pery=(float)y.total/y.popu;
return perx>pery;
}
int compare5(country x,country y){
return x.order<y.order;
}
int main(){
int a,b;
while(cin>>a>>b){
int i;
vector<country> list(a);
vector<country> list2;
for(int i=0;i<a;i++){
cin>>list[i].gold>>list[i].total>>list[i].popu;
}
int num=0;
while(b--){
cin>>i;
list2.push_back(list[i]);
list2[num].order=num;
num++;
}
sort(list2.begin(),list2.end(),compare1);
for(int i=0;i<num;i++){
list2[i].f1=i+1;
int j=i;
if(i!=0){
while(list2[j].gold==list2[j-1].gold){
list2[j].f1=list2[j-1].f1;
j--;
}
}
}
sort(list2.begin(),list2.end(),compare2);
for(int i=0;i<num;i++){
list2[i].f2=i+1;
int j=i;
if(i!=0){
while(list2[j].total==list2[j-1].total){
list2[j].f2=list2[j-1].f2;
j--;
}
}
}
sort(list2.begin(),list2.end(),compare3);
for(int i=0;i<num;i++){
list2[i].f3=i+1;
int j=i;
if(i!=0){
while(((float)list2[j].gold/list2[j].popu)==((float)list2[j-1].gold/list2[j-1].popu)){
list2[j].f3=list2[j-1].f3;
j--;
}
}
}
sort(list2.begin(),list2.end(),compare4);
for(int i=0;i<num;i++){
list2[i].f4=i+1;
int j=i;
if(i!=0){
while(((float)list2[j].total/list2[j].popu)==((float)list2[j-1].total/list2[j-1].popu)){
list2[j].f4=list2[j-1].f4;
j--;
}
}
}
sort(list2.begin(),list2.end(),compare5);
for(int i=0;i<num;i++){
int best=100000;
if(list2[i].f4<best) best=list2[i].f4;
if(list2[i].f3<=best) best=list2[i].f3;
if(list2[i].f2<=best) best=list2[i].f2;
if(list2[i].f1<=best) best=list2[i].f1;
if(best==list2[i].f1) cout<<best<<":"<<"1"<<endl;
else if(best==list2[i].f2) cout<<best<<":"<<"2"<<endl;
else if(best==list2[i].f3) cout<<best<<":"<<"3"<<endl;
else if(best==list2[i].f4) cout<<best<<":"<<"4"<<endl;
}
}
}