有没有办法在C ++中获取一系列矢量并输出CSV文件,其中CSV文件的列分别是矢量的元素?因此,第1列将是例如第一个double的向量的元素,例如
答案 0 :(得分:2)
#include <vector>
#include <fstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
// series of vectors could be put in another collection
vector<double> col1 = { 0, 1, 2 };
vector<double> col2 = { 3, 4, 5 };
vector<double> col3 = { 6, 7, 8 };
ofstream csvfile("series_vectors.csv");
if (csvfile.is_open())
{
// it is possible that the vectors are not of the same size
// if you get the maximum, then you may need to fill in empty fields
// for some of the columns
int num_of_rows = min({ col1.size(), col2.size(), col3.size() });
for (int i = 0; i < num_of_rows; i++)
{
csvfile << col1[i] << "," << col2[i] << "," << col3[i] << endl;
}
}
else
{
cout << "File could not be opened";
}
return 0;
}