我正在编写一个程序,在四个科目中输入n
学生的分数,然后根据总分数找到其中一个分数(来自codeforces.com:https://codeforces.com/problemset/problem/1017/A)。我认为将标记存储在一个结构中有助于跟踪各种主题。
现在,我所做的只是在检查总值时在向量上实现冒泡排序。我想知道,有没有一种方法可以使用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的值,而我为其他元素设置为false。通过这种方式,我可以很容易地找到托马斯的标记,即使它在矢量中的位置在根据它们的总标记进行排序后发生了变化。
也很高兴知道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
来反转排序顺序。