Printing lists with commas C++

后端 未结 28 1780
时光取名叫无心
时光取名叫无心 2020-11-22 03:33

I know how to do this in other languages, but not C++, which I am forced to use here.

I have a Set of Strings that I\'m printing to out in a list, and they need a co

28条回答
  •  忘了有多久
    2020-11-22 03:54

    Use an infix_iterator:

    // infix_iterator.h 
    // 
    // Lifted from Jerry Coffin's 's prefix_ostream_iterator 
    #if !defined(INFIX_ITERATOR_H_) 
    #define  INFIX_ITERATOR_H_ 
    #include  
    #include  
    template  > 
    class infix_ostream_iterator : 
        public std::iterator 
    { 
        std::basic_ostream *os; 
        charT const* delimiter; 
        bool first_elem; 
    public: 
        typedef charT char_type; 
        typedef traits traits_type; 
        typedef std::basic_ostream ostream_type; 
        infix_ostream_iterator(ostream_type& s) 
            : os(&s),delimiter(0), first_elem(true) 
        {} 
        infix_ostream_iterator(ostream_type& s, charT const *d) 
            : os(&s),delimiter(d), first_elem(true) 
        {} 
        infix_ostream_iterator& operator=(T const &item) 
        { 
            // Here's the only real change from ostream_iterator: 
            // Normally, the '*os << item;' would come before the 'if'. 
            if (!first_elem && delimiter != 0) 
                *os << delimiter; 
            *os << item; 
            first_elem = false; 
            return *this; 
        } 
        infix_ostream_iterator &operator*() { 
            return *this; 
        } 
        infix_ostream_iterator &operator++() { 
            return *this; 
        } 
        infix_ostream_iterator &operator++(int) { 
            return *this; 
        } 
    };     
    #endif 
    

    Usage would be something like:

    #include "infix_iterator.h"
    
    // ...
    std::copy(keywords.begin(), keywords.end(), infix_iterator(out, ","));
    

提交回复
热议问题