结构体排序sort简单 收藏

  1. #include "stdafx.h"  
  2. #include<iostream>  
  3. #include<string>  
  4. #include<algorithm>  
  5. using namespace std;  
  6. struct student  
  7. {  
  8.     string name;//姓名  
  9.     int math;//数学成绩  
  10.     int english;//英语  
  11. };  
  12. int c =0;//控制排序规则  
  13. bool compare(student a, student b)  
  14. {  
  15.     if (c == 0)//按照姓名递增排序  
  16.     {  
  17.         return (a.name<=b.name);  
  18.     }  
  19.     else if (c == 1)//按照数学成绩递增排序  
  20.     {  
  21.         return (a.math <= b.math);  
  22.     }  
  23.     else//按照英语成绩递增排序  
  24.     {  
  25.         return (a.english <= b.english);  
  26.     }  
  27. }  
  28. int _tmain(int argc, _TCHAR* argv[])  
  29. {  
  30.     student array[3];  
  31.   
  32.     array[0].name = "John";  
  33.     array[0].math = 86;  
  34.     array[0].english = 91;  
  35.   
  36.     array[1].name = "Michelle";  
  37.     array[1].math = 85;  
  38.     array[1].english =95;  
  39.   
  40.     array[2].name = "Kim";  
  41.     array[2].math = 89;  
  42.     array[2].english = 60;  
  43.     cout << "原始顺序:" << endl;  
  44.     for (int i = 0; i <3; i++)  
  45.         cout << array[i].name << ' ' << array[i].math << ' ' << array[i].english << endl;  
  46.     cout << "按姓名递增排序:" << endl;  
  47.     c =0;  
  48.     sort(array,array+3,compare);  
  49.     for (int i = 0; i <3;i++)  
  50.         cout << array[i].name << ' ' << array[i].math << ' ' << array[i].english << endl;  
  51.     cout << "按数学成绩递增排序:" << endl;  
  52.     c =1;  
  53.     sort(array, array + 3, compare);  
  54.     for (int i = 0; i <3; i++)  
  55.         cout << array[i].name << ' ' << array[i].math << ' ' << array[i].english << endl;  
  56.     system("pause");  
  57.     return 0;  
  58. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值