Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-10-27 07:13:02
Original
343 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template