首页 > 解决方案 > 如何在c ++中对具有多个条件的结构元素进行排序

问题描述

有 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;

标签: c++sortingstruct

解决方案


您可以传递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;
}

推荐阅读