In object-oriented programming, it's a common task to perform an operation between consecutive elements of a collection without introducing an unwanted trailing separator. This issue is addressed by iterating through the collection and conditionally printing the separator between elements.
Using C 11's ranged-based for loop, a verbose but effective solution is to iterate through the elements with a second iterator advanced by one:
<code class="cpp">for (auto it = items.cbegin(); it != items.cend(); it++) { cout << *it; if (std::next(it) != items.cend()) { cout << separator; } }</code>
However, this approach adds the overhead of a second iterator and obscures the main logic.
To overcome this aesthetic issue, a simpler approach is to conditionally update a string variable that holds the separator:
<code class="cpp">const auto separator = "WhatYouWantHere"; const auto* sep = ""; for (const auto& item : items) { std::cout << sep << item; sep = separator; }</code>
By initializing the sep variable to an empty string and updating it inside the loop, we ensure that the separator is printed between all elements except the last. This provides a concise and efficient solution to the problem.
The above is the detailed content of How to Iterate Through Consecutive Elements Without Extraneous Separators in C ?. For more information, please follow other related articles on the PHP Chinese website!