Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在STL-C+中按年级对学生名单进行排序+;?_C++_List_Sorting_Stl Algorithm - Fatal编程技术网

C++ 在STL-C+中按年级对学生名单进行排序+;?

C++ 在STL-C+中按年级对学生名单进行排序+;?,c++,list,sorting,stl-algorithm,C++,List,Sorting,Stl Algorithm,我有一个班级Student,有两个成员变量,其中一个是grade。我通过相应的构造函数创建一些学生,然后将他们放入列表中。然后我想使用stl库中的sort()方法,按照学生的成绩而不是姓名对学生进行排序。但是我不知道如何告诉sort()函数-我应该使用其他参数还是有其他方法 #include <iostream> #include <list> #include <string> #include <algorithm> using namespa

我有一个班级
Student
,有两个成员变量,其中一个是
grade
。我通过相应的构造函数创建一些学生,然后将他们放入
列表中。然后我想使用stl
库中的
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());

}
#包括
#包括
#包括
#包括
使用名称空间std;
班级学生{
字符串名;
双级;
公众:
学生(字符串n,双g){
name=n;
等级=g;
}
双级{
返回等级;
}
};
int main()
{
列出sp;
学生s1(“史蒂夫”,4.50),s2(“彼得”,3.40),s3(“罗伯特”,5);
sp.推回(s1);
sp.推回(s2);
sp.推回(s3);
//我想按学生的成绩对列表进行排序-我如何才能告诉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();
    });
排序(sp.begin(),sp.end(), [](恒速自动和左侧、恒速自动和右侧){ 返回lhs.getGrade()
您不能在
std::list
@NathanOliver右侧调用
std::sort
。我没注意到那是一张单子。更新的答案。如果要使用
std::sort
,则需要类似容器的
std::vector
,然后这将是一个重复: