在c ++中隐式传递数组的长度

hex*_*ode 0 c++ parameter-passing

我曾经看过代码(来自显然足够可靠的源代码,让我记住它),似乎传达了数组的长度,同时传递它们的功能(参见下面的示例):

void foo(int [m][n] array)
{
//m and n are the rows and columns of the array
//code
}
Run Code Online (Sandbox Code Playgroud)

然而,我无法找到这个来源,并开始怀疑我是否把它全部弄错了,也许,甚至想象它?有人可以评论吗?

Gal*_*lik 6

如果通过引用接受数组,则可以使用模板从参数中推导出静态大小:

template<std::size_t X, std::size_t Y>
void print(int(&array)[X][Y])
{
    for(std::size_t x = 0; x < X; ++x)
    {
        for(std::size_t y = 0; y < Y; ++y)
            std::cout << ' ' << array[x][y];
        std::cout << '\n';
    }
}

int main()
{
    int array[][3] = {{1, 3, 5}, {2, 4, 6}};

    print(array);
}
Run Code Online (Sandbox Code Playgroud)

输出:

 1 3 5
 2 4 6
Run Code Online (Sandbox Code Playgroud)