Garmaine Staff asked 2 years ago

We routinely iterate over containers with range-base for loop, or the pre-C++11 iterator based approach:

for(auto current = container.begin(); current != container.end(); ++current)

It is usually taught as a much preferred way over the "C-ish" iterations based on index increments:

for(auto currentId = 0; currentId != container.size(); ++currentId)

Yet, what if the requirement is to iterate every N th element, for example every third?

An erroneous rewrite of the above approach would give:

// Error
for(auto current = container.begin(); current != container.end(); current += 3)

Now, our programs exhibit undefined behaviour each time (container.size() % 3) != 0.

  • What would be the canonical C++ way to address such requirement?
  • Can it be done reasonably with iterator based iteration?
  • Should we fall-back to indexes (with comparison becoming <instead of !=)?