c++ - 在 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());
}
解决方案
提供要排序的谓词。并更改sp
为std::vector
. 一个 lambda 会做得很好:
std::sort(sp.begin(), sp.end(),
[](const auto& lhs, const auto& rhs) {
return lhs.getGrade() < rhs.getGrade();
});
推荐阅读
- asp.net-mvc - 如何将整个 ASP.NET MVC 网站从 www.test.com 移动到 www.test.com/xyz
- javascript - 围绕潜在获取错误进行编码的常规方法?
- python - 如何在 Pandas 中遍历 DataFrame 中的行和索引以过滤布尔值
- java - 在树莓派上使用 Jython 的 Spring Boot 应用程序
- node.js - Ubuntu 中的 npx create-react-app 错误
- pandas - Pandas 检查列表是否为 is_monotonic_increasing 但具有特定步骤
- excel - 尝试分配邮件合并以打开 excel 文件
- linux - 如何解决此交叉编译链接错误
- powerbi - 我可以从 Power BI 中的单个假设参数生成 2 个数字吗?
- python - python scipy.optimize.minimize“SLSQP求解器”在xo之间添加约束