C++ 如何将未知大小的二维数组传递给函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10164263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:41:45  来源:igfitidea点击:

How to pass two dimensional array of an unknown size to a function

c++functionpointersmatrix

提问by dasblinkenlight

I want to make class library, a function which its parameter is a matrix of unknown size, and the user will create his own matrix with his own size and pass it to this function to do some operations on his matrix like this, will be the function

我想制作一个类库,一个函数,它的参数是一个未知大小的矩阵,用户将用自己的大小创建自己的矩阵并将其传递给这个函数对他的矩阵做一些这样的操作,将是功能

calculateDeterminantOfTheMatrix( int matrix[][])
{
   some Operations to do on matrix 
}

回答by dasblinkenlight

Multi-dimensional arrays are not very well supported by the built-in components of C and C++. You can pass an N-dimension array only when you know N-1dimensions at compile time:

C 和 C++ 的内置组件并没有很好地支持多维数组。N只有N-1在编译时知道维度时,才能传递-dimension 数组:

calculateDeterminantOfTheMatrix( int matrix[][123])

However, the standard library supplies std::vectorcontainer, that works very well for multi-dimension arrays: in your case, passing vector<vector<int> > &matrixwould be the proper way of dealing with the task in C++.

但是,标准库提供了std::vector容器,它非常适用于多维数组:在您的情况下,传递vector<vector<int> > &matrix将是在 C++ 中处理任务的正确方法。

int calculateDeterminantOfTheMatrix(vector<vector<int> > &matrix) {
    int res = 0;
    for (int i = 0 ; i != matrix.size() ; i++)
        for(int j = 0 ; j != matrix[i].size() ; j++)
            res += matrix[i][j];
    return res;
}

As an added bonus, you wouldn't need to pass dimensions of the matrix to the function: matrix.size()represents the first dimension, and matrix[0].size()represents the second dimension.

作为额外的好处,您不需要将矩阵的维度传递给函数:matrix.size()表示第一维,并matrix[0].size()表示第二维。

回答by Julius

C solution:

C 解决方案:

In C you can't omit array size (except leftmost) when passing as function parameter.

在 C 中,作为函数参数传递时,不能省略数组大小(最左边除外)。

You can write: int a[]

你可以写: int a[]

but can't: int a[][]

但不能:int a[][]

just for example: int a[][20]

例如: int a[][20]

This constraint is here, because compiler needs to determine proper offsets for accessing array elements. However, you can make it this way:

这个约束在这里,因为编译器需要确定访问数组元素的适当偏移量。但是,您可以这样做:

void print_arbitrary_2D_array(void *arr, int y, int x)
{
    /* cast to 2D array type */
    double (*p_arr)[y][x] = (double (*)[y][x]) arr;

    int i, j;

    for (i = 0; i < y; ++i) {
        for (j = 0; j < x; ++j)
            printf(" %lf", (*p_arr)[i][j]);
        putchar('\n');
    }
}

double arr_1[4][3] = {
    { 3.3, 5.8, 2.3 },
    { 9.1, 3.2, 6.1 },
    { 1.2, 7.9, 9.4 },
    { 0.2, 9.5, 2.4 }
};
double arr_2[2][5] = {
    { 3.6, 1.4, 6.7, 0.1, 4.2 },
    { 8.4, 2.3, 5.9, 1.4, 8.3 }
};

print_arbitrary_2D_array(arr_1, 4, 3);
putchar('\n');
print_arbitrary_2D_array(arr_2, 2, 5);

回答by ScarletAmaranth

There are multiple approaches you could take.

您可以采取多种方法。

  1. C way of doing things -> Pass in a int**but be extremely cautious here. This is not quite a 2D array. You will have to correctly allocate memory to this pointer, or, alternatively, you need to know the size at compile time. (For instance staticly allocating an array of size M * N and then disallowing anything bigger). In order to dynamically allocate the memory, you need to know the number of rows and columns.

  2. C++ way -> #include <vector>after which you can simply use vector<vector<int> > &matrix(Careful about the space after the <int>unless you're using c++11 compiler.), which will allocate a vector of int vectors which is basically a 2d array. The memory management will be taken care of for you in this case.

  1. C 做事方式 -> 传入 aint**但在这里要格外小心。这不是一个二维数组。您必须正确地为该指针分配内存,或者,您需要在编译时知道大小。(例如静态分配一个大小为 M * N 的数组,然后禁止任何更大的数组)。为了动态分配内存,您需要知道行数和列数。

  2. C++方式->#include <vector>之后你可以简单地使用vector<vector<int> > &matrix(小心后面的空间,<int>除非你使用c++11编译器。),它将分配一个int向量的向量,它基本上是一个二维数组。在这种情况下,内存管理将为您处理。

回答by user2k5

I would write a simple class wrapper for the matrix with column and row defined.

我会为定义了列和行的矩阵编写一个简单的类包装器。

template <typename T>
class Mat {
  std::size_t _row;
  std::size_t _col;

  T *_mat_elem;
public:
  Mat(std::size_t r, std::size_t c)
   :  _row(r), _col(c), _mat_elem(new T[r*c] {}
  ~Mat() {/* remember to do delete [] here */}

  // element access, for example
  T& at(std::size_t r, std::size_t c)
  {
    return *(_mat_elem+r*_col+c);
  }
};

But actually you are re-inventing the wheels. There are good libraries for matrix handling out there.

但实际上你是在重新发明轮子。有很好的矩阵处理库。

回答by Pranu Pranav

use this method declare an array of pointers ex: int *a[n];Then allocate memory for them using a for loop ex:

使用此方法声明一个指针数组 ex: int *a[n];然后使用 for 循环 ex 为它们分配内存:

for( int i=0 ; i<n ; i++ )
        a[i] = new int[n];

Now pass the argument like normal array. ex: print_array(a,n); And print_array function looks like

现在像普通数组一样传递参数。例如:print_array(a,n); 而 print_array 函数看起来像

print_array(int **a,int n)//the prototype for the print_array
{
 //access the array using index such as
std:: cout<<a[1][1]<<endl;
}

The above case is for the array of nxn incase mxn is required then allocate the memory like

上面的情况是对于 nxn 的数组,如果需要 mxn 然后分配内存,例如

for( int i=0 ; i<m ; i++ )
        a[i] = new int[n];

then pass the both m,n and to the function and access the array in the for loop.

然后将 m,n 和都传递给函数并在 for 循环中访问数组。

回答by Muhammad_Aizaz

The Best way to use 2D array in the function that I have found so far is to use Mapping Function. As in the example below , I have use the mapping function to print 2D array

到目前为止,在我发现的函数中使用二维数组的最佳方法是使用映射函数。如下例所示,我使用映射函数打印二维数组

void Print2D(int x[],int ROWS,int COLS)
{
    for(int i=0;i<ROWS;i++)
{
    for(int j=0;j<COLS;j++)
    cout << x[i*COLS+j] << ' ';
    cout << endl;

}
}

Here it is how to use it in main

这里是如何在main中使用它

int main(){

    int x[3][3];
    Print2D(&x[0],3,3);

}

Here &x[0] is the starting address of the First Row of 2D array or more precisely Starting address of 2D array

这里 &x[0] 是二维数组第一行的起始地址或更准确地说是二维数组的起始地址