c++ - 根据元素之一对结构向量进行排序
问题描述
我正在编写一个程序来输入n
学生在四个科目中的分数,然后根据总分找到其中一个科目的排名(来自codeforces.com:https://codeforces.com/problemset/problem/1017/A) . 我认为将标记存储在结构中将有助于跟踪各种主题。
现在,我所做的只是在检查总值的同时对向量实现冒泡排序。我想知道,有没有一种方法可以使用 struct 的一个成员对向量进行排序std::sort()
?另外,我们如何让它下降?
这是代码现在的样子:
//The Structure
struct scores
{
int eng, ger, mat, his, tot, rank;
bool tommyVal;
};
//The Sort (present inside the main function)
bool sorted = false;
while (!sorted)
{
sorted = true;
for (int i = 0; i < n-1; i++)
{
if (stud[i].tot < stud[i + 1].tot)
{
std::swap(stud[i], stud[i + 1]);
sorted = false;
}
}
}
万一你有兴趣,我需要找到一个名叫托马斯的学生的等级。因此,为此,我为他的元素设置了 tommyVal 的值为 true,而为其他元素设置为 false。这样,即使在根据总分对向量进行排序后他在向量中的位置发生了变化,我也可以轻松找到 Thomas 的标记。
也很高兴知道这也std::swap()
适用于交换整个结构。我想知道它可以交换哪些其他数据结构。
解决方案
std::sort()
允许您给它一个谓词,以便您可以根据需要执行比较,例如:
std::sort(
stud.begin(),
stud.begin()+n, // <-- use stud.end() instead if n == stud.size() ...
[](const scores &a, const scores &b){ return a.tot < b.tot; }
);
只需使用return b.tot < a.tot
来反转排序顺序。
推荐阅读
- javascript - 加载外部 JS 不影响 TTI
- node.js - 无法在 Node.js 中解析 HTTP 响应正文
- java - 未选中的方法 'sort(List
)' 在 Java 11 中使用泛型调用 - sql - 如何解决 db2 代码:-104,SQL 状态:42601
- html - 如何在不使用背景图像属性的情况下覆盖图像英雄?
- javascript - 使用基于标题搜索的 JavaScript 修改 JSON 对象
- highcharts - 如何更改highchart中区域多边形的线宽?
- amazon-web-services - 应用程序负载均衡器 AWS 的 400 握手错误(Flask 和 Socket.io)
- tiles - 将 rasterize=True 与 datashader 一起使用时,如何在 count=0 的情况下获得透明度以查看底层图块?
- reactjs - 避免使用 Styled Components 和 Typescript 传递 props