C++ 结构体排序
引入头文件
#include<algorithm>
结构体
bool compare(const node &x, const node &y) {
return x.v > y.v;
}
当用 大于号就是从大到小排序
用小于号就是从小到大排序
sort 函数
sort(branch+1,branch+m+1,compare);
完整代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
typedef struct city
{
string name;
double first;
double second;
double third;
double all;
double part;
}city;
bool comparsion(city a, city b){
return a.all > b.all;
}
int main()
{
int n;
cin >> n;
vector<city> array(n);
for(int i = 0; i < n; i++){
cin >> array[i].name >> array[i].first >> array[i].second >> array[i].third;
array[i].all = array[i].first + array[i].second + array[i].third;
array[i].part = array[i].third / array[i].all;
}
sort(array.begin(), array.end(), comparsion);
string name_third;
for(int i = 0; i < 3; i++){
int max_third = 0;
if (array[i].part > max_third){
max_third = array[i].part;
name_third = array[i].name;
}
cout << array[i].name << " " << array[i].first << " " << array[i].second << " " << array[i].third << " " << array[i].all << endl;
}
cout << array[0].name << " " << name_third;
return 0;
}