今天学到了一种新的排序方法——结构体排序
假设有很多物体,对应的重量和价值分别为x,y
那么我们可以构建一个结构体
struct goods{
int x,y;
};
如果我们想根据重量从小到大排序这些物品
我们需要写一个排序条件的函数
bool cmp_score(struct goods a,struct goods b){
return a.x < b.x;
}
这个函数表示按x的升序排列物品
之后再在主函数中调用标准库sort()函数即可
像这样:
sort(a,a+n,cmp_score);
完整代码:
#include<bits/stdc++.h>
using namespace std;
struct goods{
int x,y;
}
bool cmp_score(struct goods a,struct goods b){
return a.x<c.x;
}
int main (){
int n;
cin>>n;
struct data a[n];
for(int i=0;i<n;i++) cin>>a[i].x>>a[i].y;
sort(a,a+n,smp_score);
for(int i=1;i<=n;i++)cout>>a[i].x>>" "<<a[i].y<<endl;
return 0;
}