首页 > 解决方案 > 如何先排序整数然后排序字符串?

问题描述

我正在尝试对学生的姓名和他们的分数进行排序。我想先对标记进行排序,然后对具有相同标记的学生姓名字符串进行排序。

到目前为止,这是我的代码:

#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

标签: c++

解决方案


您可以使用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可以更容易地编写从一个条目“级联”到下一个条目的比较器。


推荐阅读