【问题标题】:how to sort struct elements with multiple conditions in c++ [closed]如何在c ++中对具有多个条件的结构元素进行排序[关闭]
【发布时间】:2021-02-21 11:44:45
【问题描述】:

有 3 种蘑菇,分别命名为 C、R 和 L,每种蘑菇都有不同的重量。我想按重量和 C 是第一个 R 第二和 L 最后对它们进行排序。 例如,如果给出此列表:

L 6
R 8
C 9
L 7
C 8
C 9
R 9
L 10

那么我想要以下输出:

C 9
C 9
R 9
C 8
R 8
L 10
L 7
L 6

我尝试使用sort() 功能,首先按 R 排序,然后对 C 排序,然后按重量排序。起初这很有效,但我开始注意到这不适用于每个输入,问题是每秒sort() 忽略前一个排序,然后字母/数字到处都是。我大约 2 个月前才开始学习如何编程,所以请试着在回答时记住这一点。谢谢大家。

int sumShroom[3]{0, 0, 0};
int sumWeigth[3]{0, 0, 0};
struct shroom {
char name;
int weigth;

shroom(char _name, int _weigth)
{
    name = _name;
    weigth = _weigth;
}
};

vector<shroom> shrooms;

【问题讨论】:

  • 显示一个最小的完整示例...“我尝试过使用sort()函数”在哪里?如何?显示您尝试过的内容。还显示什么错误的输出结果。
  • std::stable_sort 如果你想排序两次,否则做一个比较器为你做双重比较。
  • std::stable_sort 如果比较一个元素然后第二个元素和第二个元素碰巧引入不同的顺序,则将无济于事。在编写排序比较器时仍然需要考虑之前的排序。
  • @Yksisarvinen 如果稳定排序按“反向”顺序(从最低到最高优先级字段)完成,它不会起作用吗?

标签: c++ sorting struct


【解决方案1】:

您可以将std::sort 传递给具有比较功能的对象。

比较函数接受 2 个参数,如果第一个参数应该早于第二个参数,则返回 true,否则返回 false

#include <iostream>
#include <vector>
#include <algorithm>

struct shroom {
    char name;
    int weigth;

    shroom(char _name, int _weigth)
    {
        name = _name;
        weigth = _weigth;
    }
};

struct shroom_cmp {
    bool operator()(const shroom& a, const shroom& b) {
        // if name is C or R, it preceeds L
        if ((a.name == 'C' || a.name == 'R') && b.name == 'L') return true;
        if (a.name == 'L' && (b.name == 'C' || b.name == 'R')) return false;
        // if both name is L, compare weigth
        if (a.name == 'L' && b.name == 'L') {
            return a.weigth > b.weigth;
        } else {
            // compare weigth first
            if (a.weigth != b.weigth) {
                return a.weigth > b.weigth;
            } else {
                // have same weigth, compare name
                return a.name == 'C' && b.name == 'R';
            }
        }
    }
};

int main(void) {
    std::vector<shroom> shrooms = {
        {'L', 6},
        {'R', 8},
        {'C', 9},
        {'L', 7},
        {'C', 8},
        {'C', 9},
        {'R', 9},
        {'L', 10}
    };

    // sort it
    std::sort(shrooms.begin(), shrooms.end(), shroom_cmp());

    // print the result
    for (const auto& s : shrooms) {
        std::cout << s.name << ' ' << s.weigth << '\n';
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    • 2013-11-07
    • 2016-01-10
    • 2012-04-15
    • 2021-07-14
    相关资源
    最近更新 更多