0

I need to make this function. The parameter suppose to be a random N*N array. And it should returns a (N-1)*(N-1) array. How can I do this?

int** SubMatrix(int** matrix){
    int** submatrix=new int*[size-1];
        ................................
        ................................
        return submatrix;
}

Is this code correct?

Besides, say in the main function, I already have this array

x={{1,2,3},{1,2,3},{1,2,3}};

How do I call the function?

Calling:

int y[2][2]=SubMatrix[x]

is wrong and

int** y=SubMatrix[x] 

is also wrong...

4

1 回答 1

0

首先,没有办法在 C++ 中跟踪数组的大小(只有分配的内存量)。因此,有必要size将数组作为参数传递或全局传递。我在以下声明中做出了这个假设:

int* SubMatrix(int** matrix, int size){
    int* submatrix = new int[(size - 1) * (size - 1)];
    // Do stuff
    return submatrix;
}

其次,如果您的矩阵是方形的,最好使用上述声明,其中分配的数组的大小是(N-1)*(N-1)(参见 Kevin Loney 的回答How do I declare a 2d array in C++ using new?关于堆上的矩阵声明);因此,该数组可作为矩阵访问。但是,访问单元格需要一些算术:

for (int i = 0; i < size - 1; ++i)
    for (int j = 0; j < size - 1; ++j)
        submatrix[i * (size -1) + j] // Element at [i][j]

最后,函数返回的数组现在是一个矩阵指针:

int* matrix = SubMatrix(matrix, size);

返回的矩阵的维度是(size-1)*(size-1)

关于你现在的例子:

x = {{1,2,3},{1,2,3},{1,2,3}};
int* y = SubMatrix(matrix, 3);
// y is now a matrix of size (size-1)*(size-1)

如果你真的(真的)想要一个二维数组:

int** SubMatrix(int** matrix, int size){
    int** submatrix = new int*[size - 1];
    for (int i = 0; i < size - 1; ++i)
        submatrix[i] = new int[size - 1]
    // Do stuff
    return submatrix;
}
于 2012-11-12T19:49:50.653 回答