How to print dimensions of multidimensional array in C++

Create a function that prints multidimensional array size by dimenstions 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


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



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.