问题
So i have a class with five integer members
struct Person {
int health;
int sport;
int relatioship;
int happiness;
int intelligence;
};
I want to know which one has the highest value, which one the second highest... Depending on the ranking of this 5 integers i want to assign them a job.
回答1:
You can sort a representation of each of the values, and use that choose the job.
enum Stat {
Health;
Sport;
Relatioship;
Happiness;
Intelligence;
};
using Stats = std::array<Stat, 5>;
using Job = std::string;
int getStat(Person p, Stat s) {
switch (s) {
case Health: return p.health;
case Sport: return p.sport;
case Relatioship: return p.relatioship;
case Happiness: return p.happiness;
case Intelligence: return p.intelligence;
}
}
Stats getStats(Person p) {
Stats result = { Health, Sport, Relatioship, Happiness, Intelligence };
std::sort(result.begin(), result.end(), [](Stat left, Stat right) { return getStat(p, left) < getStat(p, right); });
return result;
}
Job getJob(Person p) {
Stats stats = getStats(p);
if (stats == { Sport, Health, Relatioship, Happiness, Intelligence })
return "Footballer";
else if (stats == { Intelligence, Health, Sport, Relatioship, Happiness })
return "Banker";
/* 118 more entries like that */
}
回答2:
struct Person {
int health;
int sport;
int relationship;
int happiness;
int intelligence;
Person(int a, int b,int c, int d, int e)
{
health=a;
sport=b;
relationship=c;
happiness=d;
intelligence=e;
}
};
bool compare (Person a,Person b)
{
return a.health>b.health;
};
int main() {
vector<Person>v;
v.push_back(Person(1,2,3,4,5));
v.push_back(Person(2,3,4,5,6));
sort(v.begin(), v.end(),compare);
for (auto x : v)
cout << x.health << ", " << x.sport<<endl;
return 0;
}
Based off highest health:
2, 3
1, 2
Since I don't know how your comparison works it will be similar to this.
来源:https://stackoverflow.com/questions/59736433/how-to-sort-variables-that-are-not-in-an-array