Team and Player Classes
Create a Player class with the members name, age, and height.
Create a Team class with a vector holding a list of Player class instances. Add a function void add_player that adds a player to the team, a bool remove_player(const std::string& name) that removes a player from the team based on their name, and a void team_overview that prints a graph like this:
Team Overview:
Name | Age | Height
-------------------
John Doe | 25 | 6.1
Jane Smith | 22 | 5.7
Bob Johnson | 30 | 5.9
Demonstrate the structs by creating a team, creating some player objects and adding them to the team. Output the team overview before removing a player and outputting the team overview again.
- Add two constructors to the Song struct: one that takes parameters for title, artist, and length, and a default constructor that sets these values to default strings and a length of 0. Create instances of Song using both constructors and print the details.
Hint
- Use a loop to iterate over the vector for adding, removing, and displaying players.
Answer
#include <iostream>
#include <vector>
#include <string>
class Player {
public:
std::string name;
int age;
float height;
Player(const std::string& n, int a, float h) : name(n), age(a), height(h) {}
};
class Team {
private:
std::vector<Player> players;
public:
void add_player(const Player& player) {
players.push_back(player);
}
bool remove_player(const std::string& name) {
for (auto it = players.begin(); it != players.end(); ++it) {
if (it->name == name) {
players.erase(it);
return true;
}
}
return false; // Player not found
}
void team_overview() const {
std::cout << "Team Overview:\n";
std::cout << "Name | Age | Height\n";
std::cout << "-------------------\n";
for (const auto& player : players) {
std::cout << player.name << " | " << player.age << " | " << player.height << "\n";
}
}
};
int main() {
Team myTeam;
Player player1("John Doe", 25, 6.1f);
Player player2("Jane Smith", 22, 5.7f);
Player player3("Bob Johnson", 30, 5.9f);
myTeam.add_player(player1);
myTeam.add_player(player2);
myTeam.add_player(player3);
std::cout << "Initial Team:\n";
myTeam.team_overview();
std::cout << "\nRemoving 'Jane Smith':\n";
if (myTeam.remove_player("Jane Smith")) {
std::cout << "Player removed successfully.\n";
} else {
std::cout << "Player not found.\n";
}
std::cout << "\nUpdated Team:\n";
myTeam.team_overview();
return 0;
}