1、结构体排序
2、运算符重载
3、for_each 使用
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string name;
int math, chinese;
int total;
friend ostream& operator << (ostream& os, const Student& stu) {
os << stu.name.data() << ": " << stu.math << ", ";
os << stu.chinese << ", " << stu.total;
return os;
}
};
bool compTotal (const Student& s1, const Student& s2) {
return s1.total > s2.total;
}
bool compChinese (const Student& s1, const Student& s2) {
return s1.chinese > s2.chinese;
}
bool comp (const Student& s1, const Student& s2) {
if(s1.total != s2.total) return s1.total > s2.total;
return s1.chinese > s2.chinese;
}
int main()
{
vector<Student> sts {{"aaa", 70, 70, 140},{"bbb", 80, 40, 120}, {"ccc", 70, 50, 120},{"ddd", 60, 60, 120}};
// sort(sts.begin(), sts.end(), compTotal);
// for(auto& s : sts) {
// printf("%s, %d, %d, %d\n", s.name.c_str(), s.math, s.chinese, s.total);
// }
// sort(sts.begin(), sts.end(), compChinese);
// for(auto& s : sts) {
// printf("%s, %d, %d, %d\n", s.name.c_str(), s.math, s.chinese, s.total);
// }
sort(sts.begin(), sts.end(), comp);
// for(auto& s : sts) {
// cout << s << endl;
// }
for_each(sts.begin(), sts.end(), [] (const auto& stu) {
cout << stu << endl;
});
return 0;
}