【问题标题】:Passing a 2D array as Function Argument将二维数组作为函数参数传递
【发布时间】:2022-01-09 11:41:54
【问题描述】:

我正在尝试将任意大小的二维数组传递给函数。我试过的代码如下:


#include <iostream>
void func(int (&arr)[5][6])
{
    std::cout<<"func called"<<std::endl;
}
int main()
{
    int arr[5][6];
    func(arr);
    return 0;
}

如您所见,func 被正确调用。但我想传递任何大小的二维数组。在当前示例中,我们只能传递int [5][6]

PS:我知道我也可以使用vector,但我想知道是否有办法使用数组来做到这一点。例如,我应该可以写:

int arr2[10][15];
func(arr2);//this should work 

【问题讨论】:

    标签: c++ arrays function c++11 arguments


    【解决方案1】:

    您可以使用 模板 做到这一点。特别是使用nontype template parameters如下图:

    
    #include <iostream>
    //make func a function template
    template<std::size_t N, std::size_t M>
    void func(int (&arr)[N][M])
    {
        std::cout<<"func called with: "<<N<<" rows and "<<M<<" columns"<<std::endl;
    }
    int main()
    {
        int arr2[10][15];
        func(arr2);
        return 0;
    }
    

    在上面的例子中,NM 被称为非类型模板参数。

    使用模板我们甚至可以使数组中元素的类型任意,如下所示:

    //make func a function template
    template<typename T, std::size_t N, std::size_t M>
    void func(T (&arr)[N][M])
    {
        std::cout<<"func called with: "<<N<<" rows and "<<M<<" columns"<<std::endl;
    }
    int main()
    {
        int arr2[10][15];
        func(arr2);
        
        float arr3[3][4];
        func(arr3);//this works too
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      • 2021-10-17
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多