Search code examples
c++arraysobjectiterationobjectname

Iterating object names in C++


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();
    }
}

Solution

  • 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.