从文件中读取多维向量
Reading multidimensional vectors from a file
我需要将 txt 文件中的值读取到 n x 20 向量中。文件是这样的
pipe 1 2 0 1 1 50 120 5 5 6 0 0
pipe 2 3 0 1 1 50 120 4 5 2 0 0
pipe 3 4 0 1 1 25 120 1 5 4 80 90
我想出的代码如下
vector<double> aRow;
vector< vector < double >> aPipes;
ifstream inf("F:\text.txt");
while (inf >> c0 >> c1 >> c2 >> c3 >> c4 >> c5 >> c6 >> c7 >> c8 >> c9 >> c10 >> c11 >> c12)
{
if (c0 == "pipe")
{
aRow.push_back(c1);
aRow.push_back(c2);
aRow.push_back(0);
aRow.push_back(c4);
aRow.push_back(c5);
aRow.push_back(c6);
aRow.push_back(c7);
aRow.push_back(c8);
aRow.push_back(c9);
aRow.push_back(c10);
aRow.push_back(c11);
aRow.push_back(c12);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aPipes.push_back(aRow);
i++;
}
}
nNumPipes = i;
cout << "Num of pipes: " << nNumPipes << endl;
然而,当我像这样打印整个矢量时,
for (int i = 0; i < nNumPipes; i++)
{
{for (int j = 0; j < 20; j++)
cout << setprecision(3) << aPipes.at(i).at(j) << "\t";
cout << endl;
}
}
矩阵显示了所有行,但它们都与第一行重复。由于某种原因,只读取了第一行。
如有任何帮助,我们将不胜感激。
您必须清除 aRow
才能重新使用它。否则,您会一直将相同的值推入矩阵。
在aPipes.push_back(aRow);
之后添加aRow.clear();
我需要将 txt 文件中的值读取到 n x 20 向量中。文件是这样的
pipe 1 2 0 1 1 50 120 5 5 6 0 0
pipe 2 3 0 1 1 50 120 4 5 2 0 0
pipe 3 4 0 1 1 25 120 1 5 4 80 90
我想出的代码如下
vector<double> aRow;
vector< vector < double >> aPipes;
ifstream inf("F:\text.txt");
while (inf >> c0 >> c1 >> c2 >> c3 >> c4 >> c5 >> c6 >> c7 >> c8 >> c9 >> c10 >> c11 >> c12)
{
if (c0 == "pipe")
{
aRow.push_back(c1);
aRow.push_back(c2);
aRow.push_back(0);
aRow.push_back(c4);
aRow.push_back(c5);
aRow.push_back(c6);
aRow.push_back(c7);
aRow.push_back(c8);
aRow.push_back(c9);
aRow.push_back(c10);
aRow.push_back(c11);
aRow.push_back(c12);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aPipes.push_back(aRow);
i++;
}
}
nNumPipes = i;
cout << "Num of pipes: " << nNumPipes << endl;
然而,当我像这样打印整个矢量时,
for (int i = 0; i < nNumPipes; i++)
{
{for (int j = 0; j < 20; j++)
cout << setprecision(3) << aPipes.at(i).at(j) << "\t";
cout << endl;
}
}
矩阵显示了所有行,但它们都与第一行重复。由于某种原因,只读取了第一行。
如有任何帮助,我们将不胜感激。
您必须清除 aRow
才能重新使用它。否则,您会一直将相同的值推入矩阵。
在aPipes.push_back(aRow);
之后添加aRow.clear();