Using an iterator to Divide an Array into Parts with Unequal Size
<p>I have an array which I need to divide up into 3-element sub-arrays. I wanted to do this with iterators, but I end up iterating past the end of the array and segfaulting <em>even though I don't dereference the iterator</em>. given: <code>auto foo = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };</code> I'm doing:</p>

<pre><code>auto bar = cbegin(foo);

for (auto it = next(bar, 3); it &lt; foo.end(); bar = it, it = next(bar, 3)) {
    for_each(bar, it, [](const auto&amp; i) { cout &lt;&lt; i &lt;&lt; endl; });
}

for_each(bar, cend(foo), [](const auto&amp; i) { cout &lt;&lt; i &lt;&lt; endl; });
</code></pre>

<p>Now I <em>can</em> solve this by defining a <code>finish</code> iterator:</p>

<pre><code>auto bar = cbegin(foo);
auto finish = next(cend(foo), -(size(foo) % 3));

for (auto it = next(bar, 3); it != finish; bar = it, it = next(bar, 3)) {
    for_each(bar, it, [](const auto&amp; i) { cout &lt;&lt; i &lt;&lt; endl; });
}

for_each(bar, finish, [](const auto&amp; i) { cout &lt;&lt; i &lt;&lt; endl; });
for_each(finish, cend(foo), [](const auto&amp; i) { cout &lt;&lt; i &lt;&lt; endl; });
</code></pre>

<p>But this seems unnecessary when <em>I don't dereference the iterator</em>. Why can't I do the first version?</p>