游戏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条)

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?