Remove trailing comma in CSV file written for a vector using copy and ostream_iterator

前端 未结 3 1802
刺人心
刺人心 2021-01-22 12:46

I have the following function, which writes a vector to a CSV file:

#include 
#include 
#include 
#include         


        
3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-22 13:06

    There are many ways, besides already listed:

    std::string sep;
    for (const auto& x : *pdata) {
        os << x << clusAvg;
        sep = ", ";
    }
    

    or

    auto it = pdata->begin();
    if (it != pdata->end()) {
        os << *it;
        for(; it != pdata->end(); ++it)
            os << ", " << *it;
    }
    

    or

    auto it = pdata->end();
    if (it != pdata->begin()) {
        --it;
        std::copy(pdata->begin(), it, ostream_iterator(os, ", "));
        os << *it;
    }
    

提交回复
热议问题