문제

How can one iterate through an array to manipulate or access different objects and their member functions? I have 10 objects. Right now I have the same code accessing each object member function and manipulating object data basically copied and pasted for each object. I'm just wondering if there is a way to use a loop to write that code one time and have it loop through all 10 objects.

Instead of doing so manually like below:

Color red.set();
Color green.set();
Color blue.set();
Color yellow.set();
Color purple.set();
      ...

Is there a way to do this with a loop, such as the following:

colors[5] = {"red", "green", "blue", "yellow", "purple", ...};

for(int i = 0; i < 10; i++){
    Color colors[i].set();
}

I know that for PHP to do something similar would be this:

$colors = array("red", "green", "blue", "yellow", "purple" ...);

for($i = 0; $i < 10; $i++){
    ${$colors[$i]} = $colors[$i];
    // $red = "red";
}

Is it possible to do this for C++?

Below is another example as to why I am asking this and what I'm getting at: Instead of:

if(grid[row][col].ship == "red")
{
    red.setShipDamage();

    if(red.getShipSunk() == true)
        red.destroy();
}
else if(grid[row][col].ship == "green")
{
    green.setShipDamage();

    if(green.getShipSunk() == true)
        green.destroy();
}
else if( ... )

To do all of this once in a loop:

for(int i = 0; i < 10; i++)
{
    if(grid[row][col].ship == colors[i])
    {
        **colors[i]**.setShipDamage();

        if(**colors[i]**.getShipSunk() == true)
            **colors[i]**.destroy();
    }
}
도움이 되었습니까?

해결책

Your question is somewhat confusing. You need to provide what the Color class does. Is this what you want?

Color colors[5];
char *color_txt[5] = {"red", "green", "blue", "yellow", "purple"};

for (int i = 0; i < 5; i++){
    colors[i].set(color_txt[i]);
}

Based on your edited question, you can create an array of objects as I described:

Color colors[10];

Assuming each object has a default constructor. Then you can access each object through an index in the array. So your example works as expected:

for(int i = 0; i < 10; i++)
{
    if(grid[row][col].ship == colors[i])
    {
        colors[i].setShipDamage();

        if(colors[i].getShipSunk() == true)
            colors[i].destroy();
    }
}

Also, your Color class should have on overriden equality operator.

다른 팁

You need to do something like this:

std::map<std::string, Color*> colors;
colors["red"] = &red;
colors["green"] = &green;
colors["blue"] = &blue;
colors["purple"] = &purple;

///....
Color *color = colors[grid[row][col].ship];
color->setShipDamage();
if(color->getShipSunk() == true)
    color->destroy();

I hope it helps.

It's not entirely clear what it is you want to do, but here's a stab at it:

Color red, green, blue, yellow, purple;
Color *colors[5] = {&red, &green, &blue, &yellow, &purple};
for (int i = 0; i < 5; i++) {
   colors[i]->set();
}

Your example is convoluted and poorly designed to begin with. If the grid simply stored references (well, actually pointers) to the ships, you wouldn't need to loop to begin with! Consider:

if (Ship* ship = grid[y][x].ship()) {// ship() returns nullptr if there's no ship
    ship->setDamage();
    if (ship->sunk())
        // ...
}

If on the other hand you would like to associate strings with ships, you need an associative container, like unordered_map from the Standard Library:

Ship red, green, blue, white;
std::unordered_map<std::string, Ship*> = { { "red", &red },
                                           { "green", &green },
                                           /* ... */ };
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top