【发布时间】:2021-04-18 13:04:41
【问题描述】:
我正在尝试对学生的姓名和分数进行排序。我想先对分数进行排序,然后对具有相同分数的学生姓名字符串进行排序。
到目前为止,这是我的代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
struct student
{
int mark;
string name;
};
vector <student> s = {
{30, "Mark"},
{14, "Mitch"},
{23, "Hen"},
{30, "Abo"}
};
sort(s.begin(), s.end(), [](const student& a, const student& b) { return (a.mark < b.mark); });
for (const auto& x : s)
cout << x.mark << ", " << x.name << endl;
}
此代码按预期输出(排序标记):
14, Mitch
23, Hen
30, Mark
30, Abo
但是,我也希望它对具有相同成绩的学生的姓名进行排序,即 Mark 和 Abo 的分数相同,都是 30,因此 Abo 应该排在 Mark 之前(由于他们名字的字母顺序)。
预期输出:
14, Mitch
23, Hen
30, Abo
30, Mark
【问题讨论】:
-
提示:比较器 lambda 会得到更多。involved.
标签: c++