传递数组大小未知的功能 [英] Passing array with unknown size to function
问题描述
让我们说我有一个调用的函数的MyFunction(INT myarray的[] [])
,做一些数组操作。
Let's say I have a function called MyFunction(int myArray[][])
that does some array manipulations.
如果我写的参数列表那样,编译器会抱怨说,它需要知道在编译时数组的大小。有没有办法改写参数列表,以便我可以传递一个数组的大小功能?
If I write the parameter list like that, the compiler will complain that it needs to know the size of the array at compile time. Is there a way to rewrite the parameter list so that I can pass an array with any size to the function?
我的数组的大小由两个静态const int的
S IN类中定义,但是编译器不会接受像的MyFunction(INT myArray的[董事会::行数] [董事会:: COLS])
。
My array's size is defined by two static const int
s in a class, but the compiler won't accept something like MyFunction(int myArray[Board::ROWS][Board::COLS])
.
如果我可以在阵列转换为矢量,然后通过矢量的MyFunction
?有没有我可以使用或做我必须做手工转换单行转换?
What if I could convert the array to a vector and then pass the vector to MyFunction
? Is there a one-line conversion that I can use or do I have to do the conversion manually?
推荐答案
在C ++语言中,多维数组声明必须始终包括可能除了第一个所有尺寸。所以,你正在试图做的是不可能的。你不能声明内置多维数组类型的参数没有明确指定的大小。
In C++ language, multidimensional array declarations must always include all sizes except possibly the first one. So, what you are trying to do is not possible. You cannot declare a parameter of built-in multidimensional array type without explicitly specifying the sizes.
如果您需要传递运行时大小多维数组功能,可以对使用内置多维数组类型忘记。这里的一个可能的解决方法是使用一个模拟多维数组(指向其他维数组的一维数组;或通过重新计算指数模拟多维数组一个普通的一维数组)。
If you need to pass a run-time sized multidimensional array to a function, you can forget about using built-in multidimensional array type. One possible workaround here is to use a "simulated" multidimensional array (1D array of pointers to other 1D arrays; or a plain 1D array that simulates multidimensional array through index recalculation).
这篇关于传递数组大小未知的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!