c++ - 如何先排序整数然后排序字符串?
问题描述
我正在尝试对学生的姓名和他们的分数进行排序。我想先对标记进行排序,然后对具有相同标记的学生姓名字符串进行排序。
到目前为止,这是我的代码:
#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
解决方案
您可以使用std::tie:
std::sort(s.begin(), s.end(), [](const student& a, const student& b)
{ return std::tie(a.mark, a.name) < std::tie(b.mark, b.name); });
当其中一个条目中存在(没有双关语)“领带”时,使用std::tie
可以更容易地编写从一个条目“级联”到下一个条目的比较器。
推荐阅读
- visual-studio-code - VS Code 中缺少功能选择荧光笔/包装器
- javascript - 日期选择器未在某些浏览器中显示
- php - 视图laravel内部未定义的变量
- android - 如何获取 ViewHolder Recycler ViewHolder 索引
- excel - 如果在后台刷新,则不会触发包含在 Listobjects(使用 Power Query 创建)中的 QueryTables 的 After_Refresh 事件
- java - Liskov 替换原则 VS 接口隔离原则
- excel - 在 Excel 中将数字转换为单词
- python - 在 try finally 块中记录未捕获的异常
- d3.js - 条形图几乎完成,但是当移动器水平移动时,上面的数据没有更新
- dkim - 当标题“h”标签展开为 2 行时,DKIM 签名失败