Home > Article > Backend Development > How to Avoid Extraneous Separators in Iteration Loops: A C 11 Solution?
Iterating over a sequence of elements often involves printing or performing some action that needs a separator between consecutive elements. However, adding a separator after the last element can be undesirable.
When iterating over arrays with a C-style for loop, or using non-destructive iterators for unknown-size sequences, special casing the last element can prevent the extra separator:
<code class="cpp">for (const auto& item : items) { cout << item; if (std::next(it) != items.cend()) { // Not the last element cout << separator; } }</code>
Instead of explicit special casing, C 11 introduces a cleaner way to achieve this:
<code class="cpp">const auto separator = "WhatYouWantHere"; const auto* sep = ""; for (const auto& item : items) { std::cout << sep << item; sep = separator; // Only assign when not on the last element }</code>
In this approach, a pointer variable sep keeps track of whether a separator has been printed yet. When encountering the first element, sep is empty, so nothing is printed. As the loop proceeds, sep is assigned the separator value. For all subsequent elements, the separator is printed before the element.
The above is the detailed content of How to Avoid Extraneous Separators in Iteration Loops: A C 11 Solution?. For more information, please follow other related articles on the PHP Chinese website!