通过在每个元素后添加逗号将 C++ vector 转换为 CSV

标签 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;

}

我喜欢在每个元素之后添加一个逗号,如下所示: A,B,C,D

我尝试在 Google 上进行研究,但只找到 CSV 到 vector

最佳答案

循环方式:

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

“聪明”的方式:

#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();

关于通过在每个元素后添加逗号将 C++ vector 转换为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287329/

相关文章:

c++ - C++11 中将函数作为模板参数传递的新方法有哪些?

r - 从 R 中的向量列表中索引特定数值向量

c++ - 为什么 C++ 编译器找不到运算符 <<

c++ - C++:检测 vector 在函数中是否为<complex>类型

c++ - 没有匹配的成员函数调用 'push_back' ,共享指针 vector

C++ 标准库 : initialize a container by using standard input

c++ - 为什么叫 "non-type"模板参数?

c++ - double 和小数点的表示

c++ - 使用 for 循环进行线程化

python - 使用gensim的Doc2Vec生成句子向量