结构体排序,这里提供三种方法:
1.直接重写排序规则
struct Hero { string name; int age; string sex; }; int mtCompare(Hero a,Hero b) { return a.age < b.age; } int main() { Hero h[] = { {"刘备",23,"男"}, {"关羽",22,"男"}, {"张飞",20,"男"}, {"赵云",21,"男"}, {"貂蝉",19,"女"} }; sort(h,h+5,mtCompare); for (int i = 0; i < 5; i++) { cout << "姓名:" << h[i].name << " 性别:" << h[i].age << " 年龄:" << h[i].age << endl; } system("pause");
2.bool operator
型写法
operator重载小于运算符,可以设定由小到大排序,也可以设定由大到小排序 两种写法,可以写在struct内,也可以写在struct外。 这种写法区分于那种重载()运算符写法。
2.1 在struct外重载小于运算符
#include <iostream> #include <algorithm> #include<vector> using namespace std; struct Date { int a; int b; }; bool operator<(const Date &x,const Date &y) { if(x.a == y.a) return x.b>y.b; return x.a>y.a; } int main() { Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}}; sort(dat,dat+5); for(int i=0;i<5;i++) { cout<<dat[i].a<<" "<<dat[i].b<<endl; } return 0; } 输出: 5 6 3 8 3 7 2 9 1 10
2.2 在struct内重载小于运算符
#include <iostream> #include <algorithm> #include<vector> using namespace std; struct Date { int a; int b; bool operator < (const Date &y) const { return b>y.b; //设定按照b由大到小排列 } }; int main() { Date dat[5] = {{1,10},{2,9},{3,8},{3,7},{5,6}}; sort(dat,dat+5); for(int i=0;i<5;i++) { cout<<dat[i].a<<" "<<dat[i].b<<endl; } return 0; } 输出: 1 10 2 9 3 8 3 7 5 6