'How do i loop through my vectors fleetX and fleetY and access the functions in my "Ship" base class?
I want to create two fleets with maximum 9 ships and have them fight each other. I was told by my teacher i have to use shared pointers and vectors.
- Base class: Ship
- Inherited classes: Destroyer, Cruiser, Hunter
main.cpp
int main(int argc, const char * argv[]) {
std::vector<std::shared_ptr<Ship>> fleetX;
std::vector<std::shared_ptr<Ship>> fleetY;
Battlefield game;
game.createFleet(fleetX, fleetY);
return 0;
}
createFleet() in my Battlefield class
void Battlefield::createFleet(std::vector<std::shared_ptr<Ship>> fleetX, std::vector<std::shared_ptr<Ship>> fleetY) {
int hunter, destroyer, cruiser, player_Input;
// PLAYER 1
do {
cout << "BATTLEFIELD" << endl;
cout << "Player_1" << endl;
cout << "Choose the number of ships you want in your fleet (9 maximum): ";
cin >> player_Input;
} while (player_Input < 1 || player_Input > 9);
cout << endl;
do {
cout << "Choose " << player_Input << " in total ships from the following:" << endl;
cout << "HUNTER - Special Attack (Critical Hit)" << endl;
cout << "DESTROYER - Special Attack (Target Search)" << endl;
cout << "CRUISER - Special Attack (Bombardment)" << endl << endl;
cout << "HUNTER: ";
cin >> hunter;
cout << "DESTROYER: ";
cin >> destroyer;
cout << "CRUISER: ";
cin >> cruiser;
cout << endl;
} while (hunter + destroyer + cruiser != player_Input);
int iterator = 0;
while (iterator < hunter) { fleetX.push_back(std::shared_ptr<Ship>(new Hunter())); iterator++;} iterator = 0;
while (iterator < destroyer) { fleetX.push_back(std::shared_ptr<Ship>(new Destroyer())); iterator++;} iterator = 0;
while (iterator < cruiser) { fleetX.push_back(std::shared_ptr<Ship>(new Cruiser())); iterator++;} iterator = 0;
}
Solution 1:[1]
You are passing the vector by value causing a new copy to be created i.e. not modifying the original vector.
Try passing the vector by reference
void Battlefield::createFleet(
std::vector<std::shared_ptr<Ship>>& fleetX,
std::vector<std::shared_ptr<Ship>>& fleetY
) {
// rest of code
}
Edit:
Use std::make_shared<Hunter>() instead of std::shared_ptr(new Hunter())
Solution 2:[2]
You can use the Lombok Gradle plugin
Or you can use it by Gradle dependencies:
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.8'
annotationProcessor 'org.projectlombok:lombok:1.18.8'
}
You can read more about Annotation Processor in IntelliJ and Gradle
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | codingwith3dv |
| Solution 2 | Daniel Taub |
