我从一个相对较大的CSV文件中生成了一个向量,需要从每一行中生成对象。问题是,共有102列,因此手动编写对象参数是不可能的。
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];
}
}
显然,我的语法是错误的,但尽管在谷歌上搜索了很长时间,我还没有找到真正能做到这一点的东西。
要创建的对象非常简单:每列都有自己的值:
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;
(...)
换句话说,对于j=0,需要更新colNames.col0,依此类推
您看过std::vector
吗?
行是列的容器。要使用的容器是std::vector
。
我们将使用两个结构:Data_Headers
和Data_Rows
:
struct Data_Headers
{
std::vector<std::string> column_headers;
};
struct Data_Rows
{
std::vector</* data type */> column_data;
};
您可以通过以下方式访问行的数据:
Data_Type column1_data = row.column_data[0];
我想您想要做的是使用带有string
键的std::map
。例如:
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];
}
}