游戏or未来 2014-12-01 14:45 采纳率: 100%
浏览 10500
已采纳

C++list中使用sort排序

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//定义学生类
class Student
{
public:
string StuName; //姓名
string StuNum; //学号
string Sex; //性别
//成绩
float English; //英语
float SQL; //SQL
float Prob; //概率论
float Circuit; //电路
float CSharp; //C#
float Average; //平均成绩
};
list studList;

已经用list存入数据了,如何将list里的数据按平均成绩排序

  • 写回答

3条回答

  • Coursera 2014-12-02 00:33
    关注

    如果你在使用c++ 11,你可以用lambda表达式
    //用平均成绩排序
    list.sort( -> bool
    {
    return a.Average > b.Average;
    });
    //用c#成绩排序
    list.sort( -> bool
    {
    return a.Average > b.Average;
    });

    如果是c++11以下版本,你可以有用
    1. 函数
    bool compare_avaerage (const Student& first, const Student& second)
    {
    return a.Average > b.Average;
    }
    然后调用list.sort(compare_average);
    2. Function class
    class StudentSorter{
    public:
    operator() (const Student& s1, const Student& s2)
    {
    // get the field to sort by and make the comparison
    return a.Average > b.Average;
    }
    }
    然后你可以调用
    StudentSorter sorter;
    sort(list.begin(), list.end(), sorter);

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档