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

c++vector

vector<string> v;
v.push_back("A");
v.push_back("B");
v.push_back("C");
v.push_back("D");

for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
//printout 
   cout << *it << endl;

}

I like to add a comma after each element as follow:
A,B,C,D

I tried researching on Google, but I only found CSV to vector.

Best Solution

Loop way:

for (vector<string>::iterator it = v.begin(); it != v.end(); ++it) {
   if (it != v.begin()) cout << ',';
   cout << *it;
}

"Clever" way:

#include <algorithm>
#include <iterator>

if (v.size() >= 2)
   copy(v.begin(), v.end()-1, ostream_iterator<string>(cout, ","));
if (v.size() >= 1)
   cout << v.back();