如何先排序整数然后字符串?
我正在尝试对学生的姓名和他们的分数进行排序。我想先对标记进行排序,然后对具有相同标记的学生姓名字符串进行排序。
到目前为止,这是我的代码:
#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当其中一个条目中存在(没有双关语)“平局”时,使用使编写从一个条目“级联”到下一个条目的比较器更容易一些。