Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ iterating a struct

Is it possible to iterate through a struct?

For example

struct team{
   int player1;
   int player2;
   int player3;
   int player4;
   ...
   int player99; 
   int size = 99;
}

then run a for loop to set or access foo 1-4?

i guess pseudocode would look something like

for(int i = 0; i < size; i++){
    player i = (i+1); 
 }

A more simplified explanation if that doesnt make sense is I Just want to be able to go through each variable without having to hard code player1 = 1; player2 =2.

like image 457
sean Avatar asked May 29 '26 01:05

sean


1 Answers

One way is to put the players/elements into an array:

struct Team {
    static int const size = 99;
    int players[size];
};

And then:

for(int i = 0; i < size; ++i)
    int player = players[i];
like image 51
Maxim Egorushkin Avatar answered May 31 '26 15:05

Maxim Egorushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!