I have the following code
template <size_t size_x, size_t size_y>
void product(int (&arr)[size_x][size_y],int (&arr1)[size_x][size_y])
{
for (int i=0;i<size_x;i )
for (int j=0;j<size_y;j )
{
cout << "The size of a1[][] is" << arr[i][j] << endl;
}
for (int i=0;i<size_x;i )
for (int j=0;j<size_y;j )
{
cout << "The size of a1[][] is" << arr1[i][j] << endl;
}
}
int main()
{
int A[2][2] = { { 1, 2 }, { 3, 4 }};
int B[2][2] = { { 0, 5}, { 6, 7 } };
product(A,B);
return 0;
}
I am trying to pass arrays to a function. However this program works fine if the arrays are of equal dimension. I want to pass arrays with different dimensions. How can I pass an array of 22 and 32 array to a function?
CodePudding user response:
How can I pass an array of 22 and 32 array to a function?
This can be done simply by providing extra template parameters
template <size_t size_x1, size_t size_y1, size_t size_x2, size_t size_y2>
void product(int (&arr)[size_x1][size_y1],int (&arr1)[size_x2][size_y2]);
CodePudding user response:
Starting with C 20 you can use auto
as type for function parameters:
void product(auto &arr, auto &arr1)
You can get the array sizes with std::size(arr)
for the first index and std::size(*arr)
for the second index.
Complete program:
#include <iostream>
using namespace std;
void product(auto &arr, auto &arr1)
{
for (const auto &inner: arr)
for (const auto &elem: inner)
{
cout << "arr[][] is " << elem << endl;
}
for (const auto &inner: arr1)
for (const auto &elem: inner)
{
cout << "arr1[][] is " << elem << endl;
}
cout << "size of arr " << size(arr) << " * " << size(*arr) << endl;
cout << "size of arr " << size(arr1) << " * " << size(*arr1) << endl;
}
int main()
{
int A[2][2] = { { 1, 2 }, { 3, 4 }};
int B[3][1] = { { 0}, { 6 }, {3} };
product(A,B);
return 0;
}