How to print dimensions of multidimensional array in C++
Last Updated :
24 Jan, 2022
Improve
Create a function that prints multidimensional array size by dimensions i.e.:
Examples:
Input : int a[2][3][4]; printDimensions(a); Output : 2x3x4 Input : int b[5][6]; printDimensions(a); Output : 5x6
To solve this problem we should use template function to figure out the size of current array. Then we call this function recursively till the last dimension. For last dimension the boundary overridden template function should be used. The implementation of the idea:
- CPP
CPP
// C++ program to print dimensions of a // multidimensional array #include <iostream> template < typename T, size_t N> void printDimensions( const T (&a)[N]) { std::cout << N; } template < typename T, size_t N, size_t M> void printDimensions( const T (&a)[N][M]) { std::cout << N << "x"; printDimensions(a[0]); } int main() { int a[2][3][4]; printDimensions(a); return 0; } |
Output:
2x3x4
Pay attention the order of two template functions. It won’t compile if you switch them.
There is one more way to get the same results by using language template features:
- CPP
CPP
// C++ 14 program to print dimensions of a // multidimensional array #include <iostream> #include <type_traits> template < typename T> std::enable_if_t<std::rank<T>::value == 1> printDimensions( const T& a) { std::cout << std::extent<T>::value; } template < typename T> std::enable_if_t<std::rank<T>::value != 1> printDimensions( const T& a) { std::cout << std::extent<T>::value << "x"; printDimensions(a[0]); } int main() { int a[2][3][4]; printDimensions(a); return 0; } |
Output:
2x3x4
If you think that template names are too long to print you are not alone. There are short aliases in C++17:
std::extent_v for std::extent::value and std::rank_v for std::rank::value