如何在结构中记录前5个值

How to record top 5 values in struct

本文关键字:记录 5个值 结构      更新时间:2023-10-16

我在下面有这个结构

struct Income
{
    string firstname;
    string lastname;
    double income;
};
struct World
{
    Income people[100];
} myWorld;

我希望打印并显示收入前五名的名字和姓氏。

什么是整理和阅读收入并按名字打印收入前五名的好方法?

假设我在这个结构中有100个值。

您想要使用std::sort,它接受一个比较函数,类似于:

 #include <algorithm>
 using namespace std;
 vector<Income> v;
 for (auto i : myWorld.people) {
    v.push_back(i);
}
 sort(v.begin(), v.end(), [](const Income& i, const Income& j) { return i.income > j.income; });

然后简单地打印前5个,类似于:

for (size_t i = 0; i < 5;  ++i) {
    cout << v[i].firstname << " " << v[i].lastname << endl;
}