Printing lists with commas C++

后端 未结 28 1746
时光取名叫无心
时光取名叫无心 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:40

    A combination of c++11 lambda and macro:

    #define INFIX_PRINTER(os, sep)([&]()->decltype(os)&{static int f=1;os<<(f?(f=0,""):sep);return os;})()
    

    Usage:

    for(const auto& k: keywords)
        INFIX_PRINTER(out, ", ") << k;
    
    0 讨论(0)
  • 2020-11-22 03:42

    In an experimental C++17 ready compiler coming soon to you, you can use std::experimental::ostream_joiner:

    #include <algorithm>
    #include <experimental/iterator>
    #include <iostream>
    #include <iterator>
    
    int main()
    {
        int i[] = {1, 2, 3, 4, 5};
        std::copy(std::begin(i),
                  std::end(i),
                  std::experimental::make_ostream_joiner(std::cout, ", "));
    }
    

    Live examples using GCC 6.0 SVN and Clang 3.9 SVN

    0 讨论(0)
  • 2020-11-22 03:43

    I suggest you simply switch the first character with the help of a lambda.

    std::function<std::string()> f = [&]() {f = [](){ return ","; }; return ""; };                  
    
    for (auto &k : keywords)
        std::cout << f() << k;
    
    0 讨论(0)
  • 2020-11-22 03:44

    I think this should work

    while (iter != keywords.end( ))
    {
    
        out << *iter;
        iter++ ;
        if (iter != keywords.end( )) out << ", ";
    }
    
    0 讨论(0)
  • 2020-11-22 03:44

    I think this variant of @MarkB's answer strikes optimal balance of readability, simplicity and terseness:

    auto iter= keywords.begin();
    if (iter!=keywords.end()) {
        out << *iter;
        while(++iter != keywords.end())
            out << "," << *iter;
    }
    out << endl;
    
    0 讨论(0)
  • 2020-11-22 03:44

    This one overloads the stream operator. Yes global variables are evil.

    #include <iostream>
    #include <string>
    #include <vector>
    #include <algorithm>
    #include <iterator>
    
    int index = 0;
    template<typename T, template <typename, typename> class Cont>
    std::ostream& operator<<(std::ostream& os, const Cont<T, std::allocator<T>>& vec)
    {
        if (index < vec.size()) {
            if (index + 1 < vec.size())
                return os << vec[index++] << "-" << vec;
            else
                return os << vec[index++] << vec;
        } else return os;
    }
    
    int main()
    {
        std::vector<int> nums(10);
        int n{0};
        std::generate(nums.begin(), nums.end(), [&]{ return n++; });
        std::cout << nums << std::endl;
    }
    
    0 讨论(0)
提交回复
热议问题