简体   繁体   English

如何在C ++中创建返回二维数组的函数

[英]How to make a function that returns a 2-dimensional array in c++

I need to make this function. 我需要做这个功能。 The parameter suppose to be a random N*N array. 该参数假定为随机N*N数组。 And it should returns a (N-1)*(N-1) array. 并且它应该返回一个(N-1)*(N-1)数组。 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... 也是错的

First, there is no way to keep track of an array's size in C++ (only the amount of memory allocated). 首先,没有办法在C ++中跟踪数组的大小(仅跟踪分配的内存量)。 So, it is necessary that the size of the array be passed as a parameter or be global. 因此,有必要将数组的size作为参数传递或全局传递。 I make this assumption in the following declaration: 我在以下声明中做出此假设:

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

Second, if your matrix is square it may be better to use the declaration described above where the size of the array allocated is (N-1)*(N-1) (See Kevin Loney's answer How do I declare a 2d array in C++ using new? regarding matrix declaration on a heap); 其次,如果您的矩阵是方形的,则最好使用上述声明,其中分配的数组的大小为(N-1)*(N-1) (请参见Kevin Loney的答案如何在C ++中声明2d数组使用new?关于堆上的矩阵声明); thus, the array is accessible as a matrix. 因此,该数组可作为矩阵访问。 Accessing cells will, however, require a bit of arithmetic: 但是,访问单元格需要一些算法:

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]

Finally, the array returned by the function is now a matrix pointer: 最后,函数返回的数组现在是矩阵指针:

int* matrix = SubMatrix(matrix, size);

The dimensions of the matrix returned are (size-1)*(size-1) 返回的矩阵的尺寸为(size-1)*(size-1)

With respect to your example now: 现在就您的示例:

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)

If you really (really) want a two-dimensional array: 如果您真的(真的)想要一个二维数组:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM