简体   繁体   English

将csv文件转换为对象,c ++

[英]csv file to an object, c++

I've got a simple CSV file: 我有一个简单的CSV文件:

name,surname
Joe,Moe
Bob,Rob

In JavaScript I would simply create an array of objects in the following way: 在JavaScript中,我可以通过以下方式简单地创建对象数组:

// let's assume the csv file is valid and it was already processed
var csv = ["name", "surname", "Joe", "Moe", "Bob", "Rob"],
    ret = [],
    i, ilen, j, o,
    cols = 2;        

for (i = cols, ilen = csv.length; i < ilen; i += cols) {
    o = {};
    for (j = 0; j < cols; j += 1) {
       o[csv[j]] = csv[i + j];
    }
    ret.push(o);
}

console.log(ret); // [{name: "Joe", surname: "Moe"}, {name: "Bob", surname: "Rob"}]

I'd like to create a vector filled with objects (instances of a class). 我想创建一个充满对象(类实例)的向量。 The class would need to be generated during run-time, the csv file might change. 该类将需要在运行时生成,csv文件可能会更改。

Could you guide how to achieve this in c++? 您可以指导如何在C ++中实现这一目标吗?

C++ has no concept of a dynamic type that can be constructed at run-time. C ++没有可以在运行时构造的动态类型的概念。 You'll have to use collections, like std::vector<std::pair<std::string, std::string>> , which could store a row of (name, value) pairs. 您必须使用集合,例如std::vector<std::pair<std::string, std::string>> ,它可以存储一行(名称,值)对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM