Home > Backend Development > C++ > body text

How to Iterate Through Consecutive Elements Without Extraneous Separators in C ?

Linda Hamilton
Release: 2024-10-26 23:21:31
Original
841 people have browsed it

How to Iterate Through Consecutive Elements Without Extraneous Separators in C  ?

Iterating Consecutive Elements Without Extraneous Separation

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

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

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!

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