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

标签 c++ list sorting stl-algorithm

<分区>

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

}

最佳答案

提供一个谓词进行排序。并将 sp 更改为 std::vector。 lambda 会做得很好:

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

关于c++ - 按 STL - C++ 中的成绩对学生列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010970/

相关文章:

python - 在 Python 中迭代列表头部的优雅方法

perl - Perl中的递归排序

c++ std::sort 按属性对对象 vector 进行排序

python - 如何从列表中删除最后一次出现的项目?

c++ - 模板重载解决问题

java - Windows 中 Java 和 C 之间的任何 IPC 机制——不需要套接字

c++ - 提高ofstream的性能?

c# - 将列表克隆到现有列表中、最小化内存重新分配的最有效方法?

javascript - 使用比较函数js排序

C++ 组件系统问题