Home > Backend Development > C++ > How to Avoid Extraneous Separators in Iteration Loops: A C 11 Solution?

How to Avoid Extraneous Separators in Iteration Loops: A C 11 Solution?

DDD
Release: 2024-10-30 21:13:02
Original
611 people have browsed it

How to Avoid Extraneous Separators in Iteration Loops: A C  11 Solution?

Avoiding Extraneous Separators in Iteration Loops

Iterating over a sequence of elements often involves printing or performing some action that needs a separator between consecutive elements. However, adding a separator after the last element can be undesirable.

Traditional Approaches for Non-Destructive Iterators

When iterating over arrays with a C-style for loop, or using non-destructive iterators for unknown-size sequences, special casing the last element can prevent the extra separator:

<code class="cpp">for (const auto& item : items) {
    cout << item;
    if (std::next(it) != items.cend()) {  // Not the last element
        cout << separator;
    }
}</code>
Copy after login

A More Elegant Solution Using C 11 Constructs

Instead of explicit special casing, C 11 introduces a cleaner way to achieve this:

<code class="cpp">const auto separator = "WhatYouWantHere";
const auto* sep = "";
for (const auto& item : items) {
    std::cout << sep << item;
    sep = separator;  // Only assign when not on the last element
}</code>
Copy after login

In this approach, a pointer variable sep keeps track of whether a separator has been printed yet. When encountering the first element, sep is empty, so nothing is printed. As the loop proceeds, sep is assigned the separator value. For all subsequent elements, the separator is printed before the element.

The above is the detailed content of How to Avoid Extraneous Separators in Iteration Loops: A C 11 Solution?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template