Removing a comma from a c++ output

前端 未结 2 981
有刺的猬
有刺的猬 2020-12-07 03:02

I wrote this program that sorts numbers in vectors from greatest to least, it works great but the only thing that is bugging me is trying to remove the comma from the last n

2条回答
  •  时光说笑
    2020-12-07 03:57

    If begin, end are at least bidirectional iterators (as yours are), you can just check initially that begin != end; if not print nothing; if so print ", "-puncuated elements incrementing begin != std::prev(end), and finally print *begin(). like so:

    main.cpp

    #include 
    
    template
    void punctuated(OStream && out, Punct && punct, BiIter begin, BiIter end)
    {
        if (begin != end) {
            for (--end  ;begin != end; ++begin) {
                std::forward(out) << *begin << std::forward(punct);
            }
            std::forward(out) << *begin;
        }
    }
    
    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        std::vector v0;
        std::vector v1{{1}};
        std::list l{{1,2}};
        std::sets{{3,4,5,6,7}};
        std::cout << "v0 [";
        punctuated(std::cout,",",v0.begin(),v0.end());
        std::cout << "]\n";
        std::cout << "v1 [";
        punctuated(std::cout,",",v1.begin(),v1.end());
        std::cout << "]\n";
        std::cout << "l [";
        punctuated(std::cout,",",l.begin(),l.end());
        std::cout << "]\n";
        std::cout << "s [";
        punctuated(std::cout,"|",s.begin(),s.end());
        std::cout << "]\n";
        return 0;
    }
    

    Output:

    g++ -Wall -Wextra main.cpp && ./a.out
    v0 []
    v1 [1]
    l [1,2]
    s [3|4|5|6|7]
    

    Live

提交回复
热议问题