Hope
Hope

Reputation: 143

Loop through unknown number of dimensions

I want to write a loop, that can give me the dimensions of an array. I want to make it usable for any array and it should return the sizes of the dimensions.

int arr[3][5][10][9] ;
cout << "dimension 1: " << sizeof(arr)/sizeof(arr[0]) << endl; 
cout << "dimension 2: " << sizeof(arr[0])/sizeof(arr[0][0]) << endl; 
cout << "dimension 3: " << sizeof(arr[0][0])/sizeof(arr[0][0][0]) << endl;
cout << "dimension 4: " << sizeof(arr[0][0][0])/sizeof(arr[0][0][0][0]) << endl;
cout << "dimension 5: " << sizeof(arr[0][0][0][0])/sizeof(arr[0][0][0][0][0]) << endl;

This should return 3,5,10,9 (and fail for the last statement).

So the pattern seems clear "each iteration add [0] after arr. The last iteration will fail, which should stop the while-loop.

How can I "concatenate + evaluate" the array name?

I would also appreciate help on what test checks "Will this fail?", or "Is there another dimension?" in C++, as I'm just learning it.

Upvotes: 3

Views: 310

Answers (1)

Nishant Singh
Nishant Singh

Reputation: 4895

if you are using c++ 17 compiler, you can use type traits structs std::rank and std::extent as following

#include <iostream>
#include <type_traits>

template<typename T>
void print_dimension(std::size_t i) {
    if (std::rank_v<T> > 0) {
        std::cout << "Dimension " << i << ":" << std::extent_v<T> << std::endl;
        print_dimension<typename std::remove_extent_t<T>>(i + 1);
    }
}

int main() {
int arr[3][5][10][9] ;
print_dimension<decltype(arr)>(1);
return 0;
}

If you are using C++ 11/14 compiler, it would need slight modification

#include <iostream>
#include <type_traits>

template<typename T>
void print_dimension(std::size_t i) {
    if (std::rank<T>::value > 0) {
        std::cout << "Dimension " << i << ":" << std::extent<T>::value << std::endl;
        print_dimension<typename std::remove_extent<T>::type>(i + 1);
    }
}

int main() {
int arr[3][5][10][9] ;
print_dimension<decltype(arr)>(1);
return 0;
}

Upvotes: 3

Related Questions