我正在将某种算法转换为C ++(我用R语言编写,并且已经使用原始指针将其转换为C ++)。原始C ++转换的问题是,它在大型矩阵中崩溃并遭受内存泄漏(但比R快约1000倍,这是惊人的)...因此,我尝试使用向量。基本上,我有一个包含零和一的矩阵,并希望用一个表示组的数字来代替它们。 组将由水平或垂直连接的一个条目定义。 为此,我建立了一个指针矩阵并在过程中更改了它们指向的组索引。
以下代码摘录。
vector<int> groups(vector<int> matrix, int nrow, int ncol) {
vector<connection> connections;
vector<int *> pointersToIndices;
int zeroGroupIndex = 0;
int* O = &zeroGroupIndex;
int currentN = 1;
int size = nrow * ncol;
vector<int **> pointerMatrix;
for (int i = 0; i < size; i++) {
int** OO = &O;
pointerMatrix.push_back(OO);
}
int col, row, index, leftIndex, upperleftIndex, upperIndex;
for (col = 0; col < ncol; col++) {
for (row = 0; row < nrow; row++) {
index = nrow * col + row;
if (matrix[index] != 0) {
upperIndex = nrow * col + row - 1;
leftIndex = nrow * (col - 1) + row;
if (row == 0 || matrix[upperIndex] == 0) {
currentN++;
matrix[index] = currentN;
pointersToIndices.push_back(&(matrix[index]));
// I assume the following does not do what i intend
pointerMatrix[index] = &pointersToIndices.back();
}
else pointerMatrix[index] = pointerMatrix[upperIndex];
if (col != 0 && matrix[leftIndex] != 0) *pointerMatrix[index] = *pointerMatrix[leftIndex];
}
}
}
....
....
现在的问题是作业无法按我希望的那样工作。尤其是
pointerMatrix[index] = &pointersToIndices.back();
似乎失败了,因为在循环结束时,pointerMatrix
的所有元素都指向pointersToIndices
的最后一个条目,而不是正确的条目。
我希望我能澄清这个问题。 有什么建议么? 非常感谢。
答案 0 :(得分:2)
问题在于pointerToIndices
最终会在必须增长时(在多个push_back
之后)重新分配。这会使指向其元素的指针(例如在注释后的行中采用并存储的那些指针)无效,因此以后使用它们是未定义的行为。
我还没有完全理解您的算法,但是要么确保pointersToIndices
不重新分配(通过预先保留足够的空间),要么避免使用指向其元素的指针。 (或更改您的算法)。