Class
class Player {
std::string name;
int score;
int id;
};
I thought about how to write a code to sort and search vector of these classes by three criteria: name, id, and score.
The search what I want is to output the previous value and next value of the found element.
The code that I thought of
// v is a vector which the Player is randomly placed
sort(v.begin(), v.end(), [](Player& a, Player& b) {return a.getID() < b.getID(); });
std::vector<Player> ID_sorted_v = v;
sort(v.begin(), v.end(), [](Player& a, Player& b) {return a.getName() < b.getName(); });
std::vector<Player> Name_sorted_v = v;
sort(v.begin(), v.end(), [](Player& a, Player& b) {return a.getScore() < b.getScore(); });
std::vector<Player> Score_sorted_v = v;
std::cin >> input // input is ID
for (vector<Player>::iterator search =
find_if(ID_sorted_v.begin(), ID_sorted_v.end(),
[input](Player& p) {
return (p.getID() == input);
});
search != ID_sorted_v.end();
search = find_if(++search, ID_sorted_v.end(), [input](Player& p) {
return (p.getID() == input);
}
))
{
cout << *(search - 1) << endl << *search << endl << *(search + 1) << endl << endl;
}
for (vector<Player>::iterator search =
find_if(Name_sorted_v .begin(), Name_sorted_v .end(),
[input](Player& p) {
return (p.getID() == input);
});
search != Name_sorted_v .end();
search = find_if(++search, Name_sorted_v .end(), [input](Player& p) {
return (p.getID() == input);
}
))
{
cout << *(search - 1) << endl << *search << endl << *(search + 1) << endl << endl;
}
for (vector<Player>::iterator search =
find_if(Score_sorted_v.begin(), Score_sorted_v.end(),
[input](Player& p) {
return (p.getID() == input);
});
search != Score_sorted_v.end();
search = find_if(++search, Score_sorted_v.end(), [input](Player& p) {
return (p.getID() == input);
}
))
{
cout << *(search - 1) << endl << *search << endl << *(search + 1) << endl << endl;
}
Desired Results
// Player's <<Operator is overloaded
id
name:dpygiewhuodfkfu, id:27 , score:206835634
name:jcawlfye , id:30 , score:534327206
name:nwwffdkgvnegzio, id:31 , score:244395501
name
name:jcawcytbtbc , id:1535712 , score:552239646
name:jcawlfye , id:30 , score:534327206
name:jcawuqyvbttcrpq, id:559488 , score:495512171
score
name:kawuzofo , id:1030200 , score:534327131
name:jcawlfye , id:30 , score:534327206
name:intny , id:1770826 , score:534328056
I think the code is problematic in that it requires too much memory to prepare search. How can I make this code easier and simpler? I thought about it for many hours, but I couldn't think of a better way. Is that an impossible question?