[英]Passing a 2D array as Function Argument
我正在嘗試將任意大小的 2D arrays 傳遞給 function。 我嘗試過的代碼如下:
#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
您可以使用模板來做到這一點。 特別是,使用如下所示的非類型模板參數:
#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;
}
在上面的示例中, N
和M
被稱為非類型模板參數。
使用模板我們甚至可以使數組中元素的類型任意,如下所示:
//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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.