Home > Backend Development > C++ > How to Efficiently Print Comma-Separated Lists in C ?

How to Efficiently Print Comma-Separated Lists in C ?

Patricia Arquette
Release: 2024-12-30 00:01:10
Original
140 people have browsed it

How to Efficiently Print Comma-Separated Lists in C  ?

How to Print a Comma-Separated List in C ?

In C , printing a comma-separated list of elements can be tricky compared to other languages like Java. To resolve this, we explore several techniques.

Using an Infix Iterator

An infix iterator allows you to insert a delimiter between each element during iteration. It's a customized variation of the standard output iterator.

// infix_iterator.h
// Extended output iterator with delimiter insertion

template <typename T, typename charT, typename traits = std::char_traits<charT>>
class infix_ostream_iterator : public std::iterator<std::output_iterator_tag, void, void, void, void>
{
    std::basic_ostream<charT, traits>& os;
    charT const* delimiter;
    bool first_elem;

public:
    infix_ostream_iterator(std::basic_ostream<charT, traits>& s) : os(&s), delimiter(0), first_elem(true) {}
    infix_ostream_iterator(std::basic_ostream<charT, traits>& s, charT const *d) : os(&s), delimiter(d), first_elem(true) {}

    infix_ostream_iterator<T, charT, traits>& operator=(T const &item)
    {
        // Insert delimiter before element unless it's the first
        if (!first_elem && delimiter != 0)
            *os << delimiter;
        *os << item;
        first_elem = false;
        return *this;
    }
    // ...
};
Copy after login

Usage with Infix Iterator:

#include "infix_iterator.h"

// ...

// Copy elements using infix iterator to insert commas
std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ",")); 
Copy after login

The above is the detailed content of How to Efficiently Print Comma-Separated Lists 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