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

Rated as one of the most sought after skills in the industry, own the basics of coding with our C++ STL Course and master the very concepts by intense problem-solving.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
C++
Practice Tags :