[英]vector adds CSV column data into vector rows while transfering CSV file's data into c++ vector
我正在嘗試將CSV文件添加到2D數組向量中,即:向量的向量。 以下程序運行良好,但存在一個小問題,
例如,添加以下CSV數據:
1.4,23.44,24.4,3.0
2.3,4.3,44.5,6.6
3.4,33.2,5.4,3.65
我使用了以下代碼:
void Table::addTableData(string filename)
vector<vector<float> > vec;
ifstream file(filename.c_str());
bool first = false;
if (file)
{
string line;
while (getline(file,line)) //reading the data line by line
{
istringstream split(line);
float value;
int col = 0;
char sep;
while (split >> value) //
{
if(!first)
{
// Each new value read on line 1 should create a new inner vector
vec.push_back(std::vector<float>());
}
vec[col].push_back(value);
++col;
// read past the separator
split>>sep;
}
// Finished reading line 1 and creating as many inner
// vectors as required
first = true;
}
但是,上面的代碼執行並將數據添加到向量中,但不是在內部向量的第一行中添加每個值,而是在內部向量中將列添加為一行。 我的意思是說CSV文件中的行和列分別成為向量中的列和行。 如果我進行提示,則會得到以下結果
1.4 2.3 3.4
23.44 4.3 33.2
24.4 44.5 5.4
3.0 6.6 3.65
因此。 行和列顛倒了,我該如何扭轉。
感謝您查看此探針。
只需將每行添加到向量中,然后將其推回,而不是每次都添加到每個向量中:
while (getline(file,line)) //reading the data line by line
{
std::vector<float> nextRow;
// etc.
while (split >> value)
{
nextRow.push_back(value);
split >> sep;
}
vec.push_back(nextRow);
}
void Table::addTableData(string filename)
{vector> vec;
ifstream file(filename.c_str());
bool first = false;
if (file)
{
string line;
int col = 0;
while (getline(file,line)) //reading the data line by line
{
istringstream split(line);
float value;
char sep;
vec.push_back(std::vector<float>());
while (split >> value) //
{
/*
if(!first)
{
// Each new value read on line 1 should create a new inner vector
vec.push_back(std::vector<float>());
}
*/
vec[col].push_back(value);
/* ++col; */
// read past the separator
split>>sep;
}
// Finished reading line 1 and creating as many inner
// vectors as required
/* first = true; */
++col;
}
}
}
該代碼可能很好用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.