An one dimensional array, e.g., containing three integers can be defined either as std::array<int, 3> myarray or myarray[3]. Is there a container like std::array<type, size> for a multidimensional array like myarray[3][3]?
2 Answers
A key part is making sure that {} initialization works like std::array, and keeping yourself as pod-like as reasonable. Compatibility with std::array is also important, and what is more compatible than a std::array? So my solution generates the multi dimensional array out of std::arrays:
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>;
};
Sample syntax:
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 slight optimization might involve collapsing the entire array heirarchy if anything has a dimension of 0, but I'm unsure.
A multi_array<int> is an int as an aside (zero-dimensional array of ints), both because it makes sense, and because it makes the code simpler.
Here is an old version.
Comments
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;
}
1 Comment
MultiArray is no longer an aggregate.
std::array<std::array<int, 3>, 3>using Row = std::array<int, 3>; using Matrix = std::array<Row, 5>;for example.