Printing lists with commas C++

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

    If the values are std::strings you can write this nicely in a declarative style with range-v3

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        using namespace ranges;
        std::vector const vv = { "a","b","c" };
    
        auto joined = vv | view::join(',');
    
        std::cout << to_(joined) << std::endl;
    }
    

    For other types which have to be converted to string you can just add a transformation calling to_string.

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        using namespace ranges;
        std::vector const vv = { 1,2,3 };
    
        auto joined = vv | view::transform([](int x) {return std::to_string(x);})
                         | view::join(',');
        std::cout << to_(joined) << std::endl;
    }
    

提交回复
热议问题