C++ Vector to CSV by adding Comma after each element

后端 未结 5 865
梦毁少年i
梦毁少年i 2020-12-18 16:25
vector v;
v.push_back(\"A\");
v.push_back(\"B\");
v.push_back(\"C\");
v.push_back(\"D\");

for (vector::iterator it = v.begin(); it!=v.end()         


        
5条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 16:40

    To avoid the trailing comma, loop until v.end() - 1, and output v.back() for instance:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    template 
    void Out(const std::vector& v)
    {
        if (v.size() > 1)
            std::copy(v.begin(), v.end() - 1, std::ostream_iterator(std::cout, ", ")); 
        if (v.size())
            std::cout << v.back() << std::endl;
    }
    int main()
    {
        const char* strings[] = {"A", "B", "C", "D"};
        Out(std::vector(strings, strings + sizeof(strings) / sizeof(const char*)));
    
        const int ints[] = {1, 2, 3, 4};
        Out(std::vector(ints, ints + sizeof(ints) / sizeof(int)));
    }
    

    BTW you posted:

    vector v; 
    //...
    for (vector::iterator it = v.begin(); //...
    

    which is unlikely to compile :)

提交回复
热议问题