首页 > 解决方案 > 在 STL - C++ 中按学生的成绩对学生列表进行排序?

问题描述

我有一个Student有 2 个成员变量的类,其中一个是grade. 我通过相应的构造函数创建了一些学生,然后将它们放在一个list<Student>. 然后我想使用sort()stl 库中的方法,并按学生的成绩而不是他们的名字<algorithm>对学生进行排序。但是我不知道如何将这一点告诉 sort() 函数 - 我应该使用另一个参数还是有其他方法?

#include <iostream>
#include <list>
#include <string>
#include <algorithm>
using namespace std;
class Student {
    string name;
    double grade;
public:
    Student(string n, double g) {
        name = n;
        grade = g;
    }
    double getGrade() {
        return grade;
    }
};
int main()
{
    list<Student> sp;
    Student s1("Steve", 4.50), s2("Peter", 3.40), s3("Robert", 5);
    sp.push_back(s1);
    sp.push_back(s2);
    sp.push_back(s3);
    //I want to sort the list by the student's grades - how can I tell this to the sort() method?
    sort(sp.begin(), sp.end());

}

标签: c++listsortingstl-algorithm

解决方案


提供要排序的谓词。并更改spstd::vector. 一个 lambda 会做得很好:

std::sort(sp.begin(), sp.end(), 
    [](const auto& lhs, const auto& rhs) {
        return lhs.getGrade() < rhs.getGrade();
    });

推荐阅读