This function declaration
void printMatrix(const auto & matrix) {
/* print matrix using range-based for */
}
declares a template function.
Instead you could write for example
template <typename T, size_t M, size_t N>
void printMatrix(const T ( & matrix)[M][N]) {
/* print matrix using range-based for */
}
and the function is called as the previous function
printMatrix(matrix);
printMatrix(matrix2);
As the element type of the arrays is known then you can also write
template <size_t M, size_t N>
void printMatrix(const int ( & matrix)[M][N]) {
/* print matrix using range-based for */
}
//...
printMatrix(matrix);
printMatrix(matrix2);
Within the function you can use the values M
and N
in nested for loops to output the arrays as for example
for ( size_t i = 0; i < M; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
std::cout << matrix[i][j] << ' ';
}
std::cout << '\n';
}
Or you can use range-based for loop
for ( const auto &row : matrix )
{
for ( const auto &item : row )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
You could do the same using the initial function like for example
#include <iterator>
//...
void printMatrix(const auto & matrix) {
for ( size_t i = 0, m = std::size( matrix ); i < m; i++ )
{
for ( size_t j = 0, n = std::size( matrix[i] ); j < n; j++ )
{
std::cout << matrix[i][j] << ' ';
}
std::cout << '\n';
}
}
Here is a demonstration program.
#include <iostream>
#include <iterator>
std::ostream & printMatrix( const auto &matrix, std::ostream &os = std::cout )
{
for (size_t i = 0, m = std::size( matrix ); i < m; i++)
{
for (size_t j = 0, n = std::size( matrix[i] ); j < n; j++)
{
os << matrix[i][j] << ' ';
}
os << '\n';
}
return os;
}
int main()
{
int matrix[][3] =
{
{ 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 }
};
int matrix2[][6] =
{
{ 0, 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 0, 1 }, { 2, 3, 4, 5, 6, 7 }
};
printMatrix( matrix ) << '\n';
printMatrix( matrix2 ) << '\n';
}
The program output is
0 1 2
3 4 5
6 7 8
0 1 2 3 4 5
6 7 8 9 0 1
2 3 4 5 6 7