for (auto object: objects)
statement means that the data structure containing objects
is iterable, meaning that objects
data structure has implemented begin()
and end()
functions.
Now from what I understood you need to perform a particular action every 3 elements. The most simple ways to do it are:
- by using an additional counter:
size_t counter = 0;
for (auto object: objects) {
if (counter % 3 == 0) {
// modify object
}
counter ++;
}
Be aware that depending on the type objects data structure when invoking for (auto object: objects)
you might actually do a copy. (not passing the object by reference). This is due to the fact that auto takes the declination type of the element stored in objects
data structure. To make sure you really modify the object, one needs to specify that you pass the reference: for (auto & object: objects)
for instance.
- by changing the for loop statement with iterators
for (auto it = objects.begin(); it != object.end(); it ++) {
size_t element_position = std::distance(objects.begin(), it);
if (element_position % 3 == 0) {
// do something with * it which stores the object
}
}
Be cautious that std::distance
method might be linear in case that the iterator of the data structure is not a random access iterator.
For more details please have a look at:
https://www.cplusplus.com/reference/iterator/distance/