2011-03-13 69 views
0
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,dC++矢量到CSV由每個元件

我試圖研究谷歌,但我只發現了CSV到vector

回答

7

你可以輸出在for循環逗號:

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

或者,你可以使用copy算法。

std::copy(v.begin(), v.end(), std::ostream_iterator<char*>(std::cout, ", ")); 
+0

你忘了''' – 2011-03-13 04:09:33

+0

謝謝,羅布。你很快。這正是我需要的。 – AndrewS 2011-03-13 04:10:03

+1

剛剛添加的循環版本爲整個字符串添加了尾隨逗號。 – 2011-03-13 04:10:37

6

循環方式:

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

與正常的ostream_iterator,你會得到每一個數據項後一個逗號 - 包括最後,你不想要一個。

我發佈了一個infix_iteratorprevious answer修復這個問題,只在數據項之間插入逗號,而不是在最後一個之後。

+2

嘿,非常好。 – 2011-03-14 23:36:02

-1

爲了避免後面的逗號,循環,直到v.end() - 1,輸出v.back()例如:

#include <vector> 
#include <iostream> 
#include <iterator> 
#include <string> 
#include <iostream> 

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

    const int ints[] = {1, 2, 3, 4}; 
    Out(std::vector<int>(ints, ints + sizeof(ints)/sizeof(int))); 
} 

BTW你貼:

vector<string> v; 
//... 
for (vector<int>::iterator it = v.begin(); //... 

這是不太可能編譯:)

+0

不要忘記檢查'v.size()',否則你正在訪問無效的內存。 – 2011-03-14 14:42:53

+0

正確,已更正。看到你改變了你的答案:) – 2011-03-14 21:07:04

+0

是的,我們都注意到了它:P – 2011-03-14 23:35:27

0

下面應該做的工作。謝謝。

ofstream CSVToFile("ava.csv", ios::out | ios::binary); 
    //////////////////vector element to CSV//////////////////////////////////////// 
for (std::vector<string>::iterator i = ParamHeaders.begin(); i != ParamHeaders.end(); i++) 
{ 
    if (i != ParamHeaders.begin()) 
    { 
      CSVToFile << ","; 
      std::cout << ","; 
    } 
    std::cout << *i; 
    CSVToFile << *i; 

} 
+0

什麼是ParamHeaders? – 2012-12-10 21:10:30