首页 > 解决方案 > 根据元素之一对结构向量进行排序

问题描述

我正在编写一个程序来输入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()适用于交换整个结构。我想知道它可以交换哪些其他数据结构。

标签: c++sortingstructure

解决方案


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来反转排序顺序。


推荐阅读