这道题加深了对于sort函数的理解,重构排序规则 bool cmp(a,b)有了一定见解
#include<stdio.h> #include<algorithm> #include<string.h> #include<iostream> using namespace std; struct E { char name[1001]; int age; int score; }buf[1000]; bool cmp(E a, E b) { if (a.score != b.score) //比较两个数 如果a小 则为真 bool为true 排序为从小到大 即a在前b在后 return a.score < b.score; int tmp = strcmp(a.name, b.name); if (tmp != 0) return tmp < 0; else return a.age < b.age; } int main() { int n; while (cin>>n) { for (int i = 0; i < n; i++) { cin >> buf[i].name >> buf[i].age >> buf[i].score; } sort(buf, buf + n, cmp); for (int i = 0; i < n; i++) printf("%s %d %d\n", buf[i].name, buf[i].age, buf[i].score); } return 0; }
也可以直接利用C++算符重载直接定义小于运算符
#include<stdio.h> #include<algorithm> #include<string.h> #include<iostream> using namespace std; struct E { char name[1001]; int age; int score; bool operator < (const E &b) const { if (score != b.score) return score < b.score; int tmp = strcmp(name, b.name); if (tmp != 0) return tmp < 0; else return age < b.age; } }buf[1000]; int main() { int n; while (cin>>n) { for (int i = 0; i < n; i++) { cin >> buf[i].name >> buf[i].age >> buf[i].score; } sort(buf, buf + n); for (int i = 0; i < n; i++) printf("%s %d %d\n", buf[i].name, buf[i].age, buf[i].score); } return 0; }
原文:https://www.cnblogs.com/bestluna/p/14463728.html