简体   繁体   English

如何遍历向量以生成新对象?

[英]How can I iterate through a vector to generate new objects?

I've generated a vector from a relatively large CSV file and need to make objects out of each row.我已经从一个相对较大的 CSV 文件生成了一个向量,并且需要从每一行中制作对象。 Problem is, there are 102 columns, so manually writing the object parameters is out of the question.问题是,有 102 列,所以手动编写 object 参数是不可能的。

Data colNames;

for (int i = 0; i < 1; i++) {
    for (int j = 0; j < content[i].size(); j++) {
        string column = "col" + j;
        colNames.column = content[i][j];

    }
}

Obviously, my syntax is wrong, but despite long google searches, I have yet to find anything that can really do this.显然,我的语法是错误的,但是尽管谷歌搜索了很长时间,但我还没有找到任何可以真正做到这一点的东西。

The object that is to be created is very simple: each column has its own value therein:要创建的 object 非常简单:每一列都有自己的值:

class Data
{
public:
    string col0;
    string col1;
    string col2;
    string col3;
    string col4;
    string col5;
    string col6;
    string col7;
    string col8;
    string col9;
    string col10;
    string col11;
    string col12;
    string col13;
    string col14;
         (...)

In other words, for j = 0, colNames.col0 needs to be updated, and so on.换句话说,对于 j = 0,colNames.col0 需要更新,以此类推。

I guess what you want to do is use a std::map with string keys.我猜你想要做的是使用带有string键的std::map For example:例如:

std::map<std::string, std::string> colNames;

for (size_t i = 0; i < 1; i++) {
    for (size_t j = 0; j < content[i].size(); j++) {
        std::string column = "col" + std::to_string(j);
        colNames[column] = content[i][j];

    }
}

Have you looked at std::vector ?你看过std::vector吗?

A row is a container of columns .的容器。 The container to use is std::vector .要使用的容器是std::vector

We'll use two structs: Data_Headers and Data_Rows :我们将使用两个结构: Data_HeadersData_Rows

struct Data_Headers
{
    std::vector<std::string> column_headers;
};
struct Data_Rows
{
    std::vector</* data type */> column_data;
};

You can access the row's data by:您可以通过以下方式访问该行的数据:

Data_Type column1_data = row.column_data[0];

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

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