Loading... ## 第一种方法: 在sort()中传入比较器 ```cpp #include<vector> #include<algorithm> #define NUM 10 using namespace std; //自定义结构体的排序 struct Student { int id; int age; }; vector<Student> stus; bool cmd(Student a, Student b) { if (a.age < b.age) return true; return false; } void main() { for (int i = 0; i < NUM; i++) { Student s; s.id = i; s.age = rand() % 30; stus.push_back(s); } sort(stus.begin(),stus.end(),cmd); for (int i = 0; i < NUM; i++) { printf("student NO %d,age : %d\n",i,stus[i].age); } system("pause"); } ``` ## 第二种方法: 结构体内重写operator < 方法 ```cpp #include<vector> #include<algorithm> #define NUM 10 using namespace std; //重写operator < 方法 struct Student { int id; int age; bool operator < (const Student s) { return age < s.age; } }; vector<Student> stus; void main() { for (int i = 0; i < NUM; i++) { Student s; s.id = i; s.age = rand() % 30; stus.push_back(s); } sort(stus.begin(), stus.end()); for (int i = 0; i < NUM; i++) { printf("student NO %d,age : %d\n", i, stus[i].age); } system("pause"); } ``` ## 说明: 把上面的**结构体换成类**也是一样的操作方法 最后修改:2022 年 06 月 15 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 1 如果文章有用,请随意打赏。