Home  >  Article  >  Backend Development  >  How to Iterate Consecutive Pairs of Elements without an Extra Separator in C ?

How to Iterate Consecutive Pairs of Elements without an Extra Separator in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 07:13:02262browse

How to Iterate Consecutive Pairs of Elements without an Extra Separator in C  ?

Iterating Consecutive Pairs of Elements without an Extra Separator

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn