C++中的sort函数的使用(结构体排序)
题目PTA乙级1015
代码如下
#include <iostream>
#include <algorithm>
using namespace std;
const int N=100010;
//定义结构体
struct Q{
int x;
int d;
int c;
int g;
int s;
};
//将两个结构体分别传入函数
bool cmp(Q f1,Q f2)
{
//第一个放在前面就返回true
if(f1.g<f2.g)return true;
else if(f1.g==f2.g&&f1.s>f2.s)return true;
else if(f1.g==f2.g&&f1.s==f2.s&&f1.d>f2.d)return true;
else if(f1.g==f2.g&&f1.s==f2.s&&f1.d==f2.d&&f1.x<f2.x)return true;
return false;
}
int main()
{
//结构体数组
Q f[N];
int n,l,h;
cin>>n>>l>>h;
int m=n;
for(int i=0;i<n;i++){
cin>>f[i].x>>f[i].d>>f[i].c;
f[i].s=f[i].d+f[i].c;
if(f[i].d>=h&&f[i].c>=h)f[i].g=1;
else if(f[i].d>=h&&f[i].c>=l) f[i].g=2;
else if(f[i].c<h&&f[i].d<h&&f[i].d>=f[i].c&&f[i].c>=l) f[i].g=3;
else if(f[i].d>=l&&f[i].c>=l){
f[i].g=4;
}
else {
f[i].g=5;
m--;
}
}
cout<<m<<endl;
//暴力做法会超时,且相当复杂
//这里使用sort函数,在cmp函数内部进行操作
sort(f,f+n,cmp);
for(int i=0;i<m;i++)
{
cout<<f[i].x<<' '<<f[i].d<<' '<<f[i].c<<endl;
}
return 0;
}
- sort函数的调用
sort(begin,end+1,cmp)
begin为数组头,end+1为数组的最后一个元素的下一个位置
cmp返回bool类型,决定按照什么样的顺序进行排序
没有cmp,sort默认按照从小到大排序