我正在尝试将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文件中的行和列分别成为向量中的列和行。如果我做一个cout然后我得到以下结果
1.4 2.3 3.4
23.44 4.3 33.2
24.4 44.5 5.4
3.0 6.6 3.65
因此。行和列是相反的,我如何扭转局面。
感谢您查看此问题。
答案 0 :(得分:0)
只需将每行添加到矢量中,然后将其推回,而不是每次都添加到每个矢量:
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);
}
答案 1 :(得分:0)
void Table::addTableData(string filename)
{ 矢量&gt; 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;
}
}
}
此代码可能效果很好