[英]How can I iterate through a vector to generate new objects?
我已經從一個相對較大的 CSV 文件生成了一個向量,並且需要從每一行中制作對象。 問題是,有 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];
}
}
顯然,我的語法是錯誤的,但是盡管谷歌搜索了很長時間,但我還沒有找到任何可以真正做到這一點的東西。
要創建的 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;
(...)
換句話說,對於 j = 0,colNames.col0 需要更新,以此類推。
我猜你想要做的是使用帶有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];
}
}
你看過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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.