<分区>
我有一个类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());
}