When iterating over a collection of elements using ranged-based for loops, programmers often encounter the challenge of adding a separator between consecutive elements without including an unnecessary separator after the last element. Here's a concise and modern C solution to this problem:
The following C 11ish code snippet eliminates the extra separator:
<code class="cpp">const auto separator = "YourSeparatorHere"; const auto* sep = ""; for (const auto& item : items) { std::cout << sep << item; sep = separator; }</code>
By using a pointer to a const string, we avoid unnecessary string creation and memory allocation. The sep pointer is initially set to an empty string, effectively suppressing the separator for the first element.
This solution provides a concise and efficient way to iterate over a collection while separating consecutive elements without worrying about handling the special cases of the first and last elements. It allows programmers to focus on the core logic without being distracted by implementation details.
The above is the detailed content of How to Iterate Consecutive Pairs of Elements without an Extra Separator in C ?. For more information, please follow other related articles on the PHP Chinese website!