Luc*_*mos 3 c++ arrays matrix dynamic-memory-allocation
我正在编写一个读取文本文件以动态创建矩阵的代码。然后我将从这个矩阵中获取信息以将其写入另一个文本文件。
我放入了一个“for”循环,它将为它读取的每个文本块创建一个矩阵,这里是:
for (cont = 0; cont < nPares; cont++){
ResultFile >> FlowOri;
ResultFile >> FlowDest;
ResultFile >> nPaths;
ResultFile >> largestPath;
double** iPathMatrix = (double**) new double[nPaths];
for (i = 0; i < nPaths; i++) {
iPathMatrix[i] = (double*) new double[largestPath + 2];
}
for (i = 0; i < nPaths; i++) {
for (j = 0; j < largestPath + 2; j++) {
ResultFile >> iPathMatrix[i][j];
}
}
for (i = 0; i < nPaths; i++) {
for (j = 0; j < largestPath + 2; j++) {
cout << iPathMatrix[i][j] << " ";
}
cout << "\n";
}
free(iPathMatrix);
}
Run Code Online (Sandbox Code Playgroud)
'ResultFile' 是一个 ifstream。靠近末尾的那个“cout”被放在那里以检查它是否按预期创建矩阵,它是。
如您所见,我正在创建矩阵,然后在循环结束时释放内存以再次创建它,因为它将具有相同的名称。我可能可以想出一种方法来处理这个问题,但是如果我可以为每个循环创建一个不同的矩阵会更容易,也许可以使用“FlowOri”和“FlowDest”变量命名每个矩阵,如果可能的话,并在循环停止,访问它们并写入我的输出文件。
有没有办法做到这一点?之后我将如何引用它?
如您所见,我正在创建矩阵,然后在循环结束时释放内存以再次创建它,
不,你不是(至少不正确)。每个 new[] 必须与一个 delete[] 配对,所以正确的代码是
for (i = 0; i < nPaths; i++) {
delete[] iPathMatrix[i];
}
delete[] iPathMatrix;
Run Code Online (Sandbox Code Playgroud)
现在,由于您正在编写 C++,因此可以通过使用向量来避免这种情况。
std::vector<std::vector<double>> iPathMatrix(nPaths, std::vector<double>(largestPath + 2));
Run Code Online (Sandbox Code Playgroud)
现在你不需要分配或释放任何东西,但你的其余代码没有改变。
现在至于你的实际问题。如果我理解正确,您希望将矩阵与flowOri变量的值相关联。这很容易做到,您应该使用std::map.
你还没有说是什么类型flowOri,我假设它是 astd::string但你应该能够让它工作无论它是什么类型。
#include <vector>
#include <map>
#include <string>
// lets give a shorter name for the vector type
using MatrixRowType = std::vector<double>;
using MatrixType = std::vector<MatrixRowType>;
// and this is the map type that holds the matrices
using MatrixMapType = std::map<std::string, MatrixType>;
...
MatrixMapType matrixMap;
for (cont = 0; cont < nPares; cont++){
// read stuff
ResultFile >> FlowOri;
...
// read the matrix
MatrixType iPathMatrix(nPaths, MatrixRowType(largestPath + 2));
...
// save the matrix in the map keyed by FlowOri
matrixMap[FlowOri] = iPathMatrix;
}
Run Code Online (Sandbox Code Playgroud)
现在,当你想检索一个 matirx 时,你只需写一个变量matrixMap[something]wheresomething是你想要检索的矩阵的名称。