iterate through object?

Hey there..

I'm in learning but I stuck a little and can't get it understood..

there is this class and "I would need" 16 instances of it.. in my opinion it would make sense to make some 16 variables inside the class, so the object has them all

..but i need to interate through the object.. and I don't get it, how I could get this managed?
is there something similar to foreach() from PHP?

or could I put the 16 objects in a array?

I’m not much of a C++ programmer (C is more my baby) so it might be a stupid approach from my side but you can give it a try

myClass instances[16];

void setup()
{
  for(int cnt = 0;cnt < sizeof(instances) / sizeof(instances[0]); cnt++)
  {
    ...
    ...
  }
}

Whoa there cowboy… Its easier than that…

myClass instances[16];

void setup()
{
  for(int cnt = 0;cnt < 16; cnt++)
  {
    ...
    ...
    instances[cnt].method(...);
    ...
  }
}

-jim lee

hey guys... worked :smiley: .. thank you very much :))

jimLee:
Whoa there cowboy.. Its easier than that..

-jim lee

And even more so...

lol :stuck_out_tongue:

myClass instances[16];
 
void setup()
{
  for(auto &item : instances){
    item.method();
  }
}

hey :smiley: .. nice :slight_smile:

Wait a sec.. What was that?

for(auto &item : instances){
    item.method();
  }

Never seen anything like it.

-jim lee

jimLee:
Whoa there cowboy.. Its easier than that..
...
...

-jim lee

Not flexible :wink: Increase the number of instances and you have must not forget to update the for-loop.

jimLee:
Wait a sec… What was that?

Never seen anything like it.

-jim lee

It is a ranged for loop or if you are familiar with other languages a for-each loop. Its downside is there is no index, but if you are acting on each element in an array it is useful.

Also, by adding begin() and end() functions to objects, you can also iterate those. For instance I have added them to the String library and I also included the functionality into the EEPROM library I wrote (built into IDE).

This is a pretty much unknown feature of the library as it stands… never had any questions about it:

Example to zero the EEPROM:

#include <EEPROM.h>

void setup(){

  for( auto cell : EEPROM ){
    cell = 0;
  }
}

void loop(){}