Iterating over Consecutive Element Pairs with C Idioms
One common programming task is iterating over a collection and performing an action between each consecutive pair of elements. While a basic ranged-for loop can handle the iteration, it often results in an unwanted separator at the end.
Fortunately, there are several idiomatic approaches to resolve this issue. One method involves using an additional pointer to track the separator state:
<code class="cpp">const auto separator = "WhatYouWantHere"; const auto* sep = ""; for(const auto& item : items) { std::cout << sep << item; sep = separator; }
In this example, the sep pointer is initialized to an empty string. As the loop progresses, sep is updated with the separator string whenever a non-final element is encountered. By default, sep will be an empty string before the first element, resulting in no leading separator.
Alternatively, some C libraries provide specialized iterators that handle the separator logic. For instance, the Boost Range library includes the adjacent_filtered function, which can be used to apply a predicate to successive element pairs and filter out any that fail the predicate:
<code class="cpp">#include <boost/range/algorithm/adjacent_filtered.hpp> for(auto& adjacent_pair : boost::adjacent_filtered(items, [](const auto& lhs, const auto& rhs) { return lhs != rhs; })) { std::cout << adjacent_pair.first << " separator " << adjacent_pair.second; }</code>
This approach provides a concise and elegant solution, but requires the use of an external library. Ultimately, the choice of which idiom to use depends on the specific needs and preferences of the programmer.
The above is the detailed content of How to Iterate Over Consecutive Element Pairs in C without Unwanted Separators?. For more information, please follow other related articles on the PHP Chinese website!