C :构成CSV文件列的向量

C++ : Vectors forming the columns of a CSV file?

本文关键字:向量 文件 CSV 构成      更新时间:2023-10-16

是否有一种方法可以在C 中使用一系列向量并输出一个CSV文件,其中CSV文件的列分别是向量的元素?因此,第1列将是示例的第一个双矢量的元素。

#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;
}