Summing elements in a vector

So, what you want to do is:

  1. Loop through the vector.
  2. Sum every 12 elements.

The code should then reflect this as close as possible. This can be done, as you supposed, through a nested loop:

// A loop through the whole vector.
for (...) {
    ...
    // A loop to sum 12 elements.
    for (...) { ... }
    ...
}

The tricky bit is what goes inside the for loops' (...). The key is to consider that the loop through the whole vector need not step through it one element at a time. Why not loop through it 12 elements at a time?

for (auto i = 0u; i < v.size(); i += 12) { ... }

This will make writing the inner loop much easier:

for (auto i = 0u; i < v.size(); i += 12) {
    ...
    for (auto j = i; j < i + 12 && j < v.size(); ++j) { ... }
    ...
}

The condition j < i + 12 && j < v.size() accounts for two things: first, it loops until the 12th element from the current position i. Second, the size of the vector v may not necessarily be a multiple of 12, so you must be mindful of when the range ends prematurely. You could write it like this as well, if the logic is more apparent:

for (auto i = 0u; i < v.size(); i += 12) {
    ...
    for (auto j = i; j < i + 12; ++j) {
        if (!(j < v.size())) break;
        ...
    }
    ...
}

To make this more readable and less error-prone, we can move the 12 (currently a magic number) into a proper constant:

auto constexpr step = 12;

for (auto i = 0u; i < v.size(); i += step) {
    ...
    for (auto j = i; j < i + step && j < v.size(); ++j) { ... }
    ...
}

In this way, the purpose of the value 12 can be more apparent, and follows the Single Responsibility/Don't Repeat Yourself principles. If you want to change the step size, you won't have to do it in two places anymore (easy source of mistakes).

You should be able to fill out the rest of the ... on your own. Let me know if anything was unclear or needs further elaboration.

/r/cpp_questions Thread