重载小于号运算符
平常写代码没怎么用过这种方法,因为语法不是很熟
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 310;
struct Person{
int id,sum,a,b,c;
bool operator< (const Person &t) const{
if(sum != t.sum) return sum>t.sum;
if(a != t.a) return a>t.a;
return id<t.id;
}
}q[N];
int n;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int a,b,c;
cin>>a>>b>>c;
q[i] = {i, a+b+c, a,b,c};
}
sort(q+1, q+n+1);
for(int i=1;i<=5;i++)
cout<<q[i].id<<' '<<q[i].sum<<endl;
return 0;
}
重写比较函数(都忘了比较函数怎么写的)
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 310;
struct Person{
int id,sum,a,b,c;
}q[N];
bool cmp(Person& a,Person& b){
if(a.sum!=b.sum) return a.sum>b.sum;
if(a.a!=b.a) return a.a>b.a;
return a.id<b.id;
}
int n;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int a,b,c;
cin>>a>>b>>c;
q[i] = {i, a+b+c, a,b,c};
}
sort(q+1, q+n+1,cmp);
for(int i=1;i<=5;i++)
cout<<q[i].id<<' '<<q[i].sum<<endl;
return 0;
}
lambda写法
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 310;
struct Person{
int id,sum,a,b,c;
}q[N];
int n;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int a,b,c;
cin>>a>>b>>c;
q[i] = {i, a+b+c, a,b,c};
}
sort(q+1, q+n+1, [](Person& a,Person& b) {
if(a.sum != b.sum) return a.sum>b.sum;
if(a.a != b.a) return a.a>b.a;
return a.id<b.id;
});
for(int i=1;i<=5;i++)
cout<<q[i].id<<' '<<q[i].sum<<endl;
return 0;
}