简体   繁体   中英

csv file to an object, c++

I've got a simple CSV file:

name,surname
Joe,Moe
Bob,Rob

In JavaScript I would simply create an array of objects in the following way:

// 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.

Could you guide how to achieve this in c++?

C++ has no concept of a dynamic type that can be constructed at run-time. You'll have to use collections, like std::vector<std::pair<std::string, std::string>> , which could store a row of (name, value) pairs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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