好的,所以你有一个数组A [] ...在一些函数中传递给你,比如说下面的函数原型:
void foo(int A[]);
Run Code Online (Sandbox Code Playgroud)
好的,正如你所知,在不知道某种结束变量或已知大小的情况下很难找到该数组的大小......
那么这里是交易.我似乎有些人在挑战问题上找到了解决方法,我不明白他们是如何做到这一点的.我当然无法看到他们的源代码,这就是我在这里问的原因.
有谁知道甚至可以远程查找该数组的大小?也许类似于C语言中free()函数的作用?
你觉得这怎么样??
template<typename E, int size>
int ArrLength(E(&)[size]){return size;}
void main()
{
int arr[17];
int sizeofArray = ArrLength(arr);
}
Run Code Online (Sandbox Code Playgroud)
该函数的签名是不服用阵列的功能的,而是一个指针到int.您无法在函数中获取数组的大小,并且必须将其作为函数的额外参数传递.
如果您被允许更改功能的签名,则有不同的选择:
C/C++(简单):
void f( int *data, int size ); // function
f( array, sizeof array/sizeof array[0] ); // caller code
Run Code Online (Sandbox Code Playgroud)
C++:
template <int N>
void f( int (&array)[N] ); // Inside f, size N embedded in type
f( array ); // caller code
Run Code Online (Sandbox Code Playgroud)
C++(虽然是一个调度):
template <int N>
void f( int (&array)[N] ) { // Dispatcher
f( array, N );
}
void f( int *array, int size ); // Actual function, as per option 1
f( array ); // Compiler processes the type as per 2
Run Code Online (Sandbox Code Playgroud)