结构体排序的三种方式 |
您所在的位置:网站首页 › 结构体数组数值排序 › 结构体排序的三种方式 |
目录
方式1 lambda表达式方式2 重载小于号方式3 实现cmp()函数
方式1 lambda表达式
使用lambda表达式来完成sort()函数的第3个参数,十分优雅,强烈推荐。 语法为 [](Student a, Student b){return a.ChineseGrade >= b.ChineseGrade;}完整程序如下, #include #include using namespace std; struct Student { string name; int MathGrade; int ChineseGrade; }; int main() { Student students[5]; students[0] = {"赵", 10, 20}; students[1] = {"钱", 20, 40}; students[2] = {"孙", 50, 30}; students[3] = {"李", 40, 10}; students[4] = {"王", 30, 50}; //语文成绩大的学生排在前面,结构体中的变量ChineseGrade sort(students, students+5, [](Student a, Student b){return a.ChineseGrade >= b.ChineseGrade;}); for(int i = 0; i |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |