How to use the std :: array <type, size> container for a multidimensional array in C ++ 11?

A one-dimensional array, for example, containing three integers, can be defined as std::array<int, 3> myarray or myarray[3] . Is there a container of type std::array<type, size> for a multidimensional array of type myarray[3][3] ?

+6
source share
2 answers

This should work:

 template<typename T, std::size_t Size, std::size_t ...Sizes> struct MultiArray : public std::array<MultiArray<T, Sizes...>, Size> { }; template<typename T, std::size_t Size> struct MultiArray<T, Size> : public std::array<T, Size> { }; int main() { MultiArray<int, 3, 6, 8> ma; std::cout << ma.size() << std::endl; std::cout << ma[0].size() << std::endl; std::cout << ma[0][0].size() << std::endl; ma[2][1][6] = 4; } 
+4
source

The key part is to make sure that the {} initialization works like std::array , and keeps itself as similar as reasonable. Compatibility with std::array also important, but what is more compatible than std::array ? So my solution generates a multidimensional array from std::array s:

 template<class T, size_t... sizes> struct multi_array_helper { using type=T; }; template<class T, size_t... sizes> using multi_array = typename multi_array_helper<T, sizes...>::type; template<class T, size_t s0, size_t... sizes> struct multi_array_helper<T, s0, sizes...> { using type=std::array<multi_array<T, sizes...>, s0>; }; 

living example

Syntax Example:

 multi_array<int, 2,2> arr = {{ {{0,1}}, {{2,3}} }}; static_assert( std::is_same< multi_array<int,2,2>, std::array<std::array<int,2>,2> >{}, "see, just arrays under the hood" ); 

A small optimization may include folding the entire hierarchy of the array if something has dimension 0, but I'm not sure.

A multi_array<int> is an int as a third-party (zero-dimensional array of int s), since it makes sense and because it makes the code simpler.


Here is the old version .

+5
source

Source: https://habr.com/ru/post/981941/


All Articles