You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于单个成员变量对Student对象数组进行排序?

按score对Student数组排序的正确实现

你可以直接使用std::sort配合lambda表达式完成排序,核心是在lambda中定义两个Student对象的比较规则。以下是完整的修正代码,重点看排序部分:

#include <fstream>
#include <algorithm>

// 补充缺失的宏定义和变量声明
#define MAX_M 100 // 根据实际需求调整大小
int m;

class Student
{
public:
    int score;

    //other stuff

    void construct(std::ifstream& _f)
    {
        _f >> score;
        //does other initialising as well
    }

};

int main()
{
    std::ifstream inf("input.in");
    inf >> m;
    Student* students = new Student[MAX_M]; //creates the array
    for (int i = 0; i < m; ++i)
    {
        students[i].construct(inf); //inf is the input file
    }
    inf.close();

    // 按score升序排序(从小到大)
    std::sort(students, students + m, [](const Student& a, const Student& b) {
        return a.score < b.score;
    });

    // 如果需要降序排序(从大到小),把比较符改成>即可
    // std::sort(students, students + m, [](const Student& a, const Student& b) {
    //     return a.score > b.score;
    // });
}

关键说明:

  • std::sort的前两个参数是排序范围的起始和结束边界(对于数组来说,直接用指针即可,students是起始地址,students + m是结束地址的下一个位置)。
  • 第三个参数是lambda表达式,接收两个const Student&类型的参数(用引用避免拷贝,提升效率),返回bool值表示第一个参数是否应该排在第二个参数前面:
    • 升序用a.score < b.score:当a的分数小于b时,a排在b前面。
    • 降序用a.score > b.score:当a的分数大于b时,a排在b前面。

另外,你的原代码里缺失MAX_M的宏定义和m的变量声明,上面的代码已经补充了这部分,你可以根据实际需求调整MAX_M的大小。

内容的提问来源于stack exchange,提问作者Παναγιώτης Ρήγκος

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:17:08