6

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]?

3
  • 7
    std::array<std::array<int, 3>, 3> Commented Feb 3, 2015 at 22:13
  • If you only ever use arrays of the same size, it might be a good idea to use a few typedefs: using Row = std::array<int, 3>; using Matrix = std::array<Row, 5>; for example. Commented Feb 3, 2015 at 22:29
  • @AntonSavin: That is an answer. Why are you posting a comment with the answer in it? Question comments are for requesting clarification and pointing out problems with the question itself. Commented Feb 4, 2015 at 1:33

2 Answers 2

4

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

live example

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

The downside is that MultiArray is no longer an aggregate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.