【问题标题】:How to sort integer first then string?如何先排序整数然后排序字符串?
【发布时间】: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++


【解决方案1】:

你可以使用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 可以更轻松地编写比较器,当其中一个条目中存在(不是双关语)“平局”时,从一个条目“级联”到下一个条目。

【讨论】:

    【解决方案2】:

    您应该使用符合您的规范的比较函数。

    sort(s.begin(), s.end(),
        [](const student& a, const student& b) {
            return
                a.mark < b.mark // a < b if a.mark is less than b.mark
                ||
                (a.mark == b.mark && // when a.mark equals to b.mark
                 a.name < b.name);   // compare their name
        }
    );
    

    【讨论】:

    • 嘿 @MikeCAT 谢谢你的回答,我只是将类拆分为 .h 文件,我收到此错误 Error C2664 'bool main: ::operator ()(const Student &, const Student &) const': 无法将参数 1 从 'Student *' 转换为 'const Student &' 知道我为什么会这样吗?
    • 看起来是因为您正在传递 Student* ,而 Student 是预期的。
    • 嘿 @MikeCAT 感谢您的快速回复,错误消失了,但出现了另一个错误,错误 C2440 'initializing': cannot convert from 'student' to 'student',知道为什么吗?感谢您的时间。欣赏它
    【解决方案3】:

    您可以使用三元运算符来检查标记是否相等,如果相等,则比较名称;否则只需比较分数:

    sort(s.begin(), s.end(), [](const student& a, const student& b) {
        return (a.mark == b.mark) ? (a.name < b.name) : (a.mark < b.mark); }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2021-09-13
      • 2013-06-29
      • 1970-01-01
      • 2021-11-28
      • 2018-03-11
      • 1970-01-01
      相关资源
      最近更新 更多