在STL - C++中按成绩对学生列表进行排序?

Sorting a list of students by their grades in STL - C++?

本文关键字:列表 排序 STL C++      更新时间:2023-10-16

我有一个类Student,其中包含 2 个成员变量,其中一个是grade。我通过相应的构造函数创建一些学生,然后将它们放入list<Student>中。然后,我想在 stl<algorithm>库中使用sort()方法,并按成绩而不是姓名对学生进行排序。但是我不知道如何告诉 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());
}

提供要排序的谓词。并将sp改为std::vector.一个 lambda 会做得很好:

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