1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
// Example program
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> // sort
struct Player {
std::string name;
double avg_points;
int jersey_number;
struct compareByName {
bool operator()(const Player& a, const Player& b)
{
return a.name < b.name;
}
};
struct compareByAveragePoints {
bool operator()(const Player& a, const Player& b)
{
return a.avg_points < b.avg_points;
}
};
struct compareByJerseyNumber {
bool operator()(const Player& a, const Player& b)
{
return a.jersey_number < b.jersey_number;
}
};
};
void print(const std::vector<Player>& basketball_team, const std::string& sort_method)
{
std::cout << "Sorted by " << sort_method << ":\n ";
for (const auto& player : basketball_team)
std::cout << player.name << " " << player.avg_points << " " << player.jersey_number << "\n ";
std::cout << std::endl;
}
int main()
{
std::vector<Player> basketball_team {
{ "Michael Jordan", 50, 1 },
{ "Magic Johnson", 35.2, 2 },
{ "Shaq Oneal", 29, 3 },
{ "LeBron James", 35.1, 17 }
};
std::sort(basketball_team.begin(), basketball_team.end(), Player::compareByName());
print(basketball_team, "Name");
std::sort(basketball_team.begin(), basketball_team.end(), Player::compareByAveragePoints());
print(basketball_team, "Average Points");
std::sort(basketball_team.begin(), basketball_team.end(), Player::compareByJerseyNumber());
print(basketball_team, "Jersey Number");
}
|