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;
}
Run Code Online (Sandbox Code Playgroud)
我想在每个元素之后添加一个逗号,如下所示: A,B,C,D
我尝试过研究Google,但我只发现了CSV vector.
您可以在for循环中输出逗号:
for (vector<int>::iterator it = v.begin(); it!=v.end(); ++it) {
//printout
cout << *it << ", " << endl;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用该copy算法.
std::copy(v.begin(), v.end(), std::ostream_iterator<char*>(std::cout, ", "));
Run Code Online (Sandbox Code Playgroud)
循环方式:
for (vector<string>::iterator it = v.begin(); it != v.end(); ++it) {
if (it != v.begin()) cout << ',';
cout << *it;
}
Run Code Online (Sandbox Code Playgroud)
"聪明"的方式:
#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();
Run Code Online (Sandbox Code Playgroud)