c++ - 如何在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;
解决方案
您可以传递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;
}
推荐阅读
- database - 运输区 - 表费率 - 不保存信息
- vue.js - 如何使用 wepack devserver 代理静态文件?
- python - TypeError:“类”对象不可迭代-flask/sqlalchemy/jinja
- python - 在烧瓶应用程序中使用 sqlalchemy 更新 postgresql 记录
- python - python:测试文本字段中是否存在多个字符串以设置新列值
- .net-core - contentrootpath 指向 C:/Program Files/IISExpress
- reactjs - Focus Trap React 和 2 个弹出窗口中的一些组件
- android - 在 Ubuntu 中为 HAXM 获取更多可用内存
- c++ - 如何在 C++ 中编写此伪代码?函数返回两个数组到两个初始化的数组
- dart - 你可以在 Dart 中将扩展方法作为函数参数传递吗?