根据其中一个元素对结构向量进行排序
Sorting a vector of structures based on one of the elements
我正在写一个程序来输入 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;
}
}
}
以防万一你感兴趣,我需要找到一个叫 Thomas 的学生的排名。因此,为此,我将他的元素的 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
反转排序即可。
我正在写一个程序来输入 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;
}
}
}
以防万一你感兴趣,我需要找到一个叫 Thomas 的学生的排名。因此,为此,我将他的元素的 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
反转排序即可。