One-line initialiser for Boost.MultiArray

房东的猫 提交于 2019-11-30 09:38:49

You can encapsulate the creation of the array into an helper function:

template <typename T, size_t N>
boost::multi_array<T, N> make_regular_matrix(const size_t m)
{
    boost::multi_array<T, N> arr;
    boost::array<size_t, N> extents;
    extents.assign(m);
    arr.resize(extents);

    return arr;
}

const int n = 3;
int size = 4; // Can be const as well, but this is not mandatory

auto arr = make_regular_matrix<char, n>(size);

If you can't use auto, you'll have to duplicate the template parameters:

boost::multi_array<char, n> arr = make_regular_matrix<char, n>(size);

The make_regular_matrix function could be shortened to use std::vector, as you did in your answer; I don't know if this implementation would be better. The aim of the helper function is to hide the creation of the array, but other versions could be written, for example to initialize the array elements with a given value:

template <size_t N, typename T> //switched order for deduction
boost::multi_array<T, N> make_regular_matrix(const size_t m, const T & value)
{
     boost::multi_array<T, N> arr(std::vector<size_t>(n, m));

     std::fill(arr.data(), arr.data() + arr.num_elements(), value);

     return arr;
}

auto arr = make_regular_matrix<4>(3, 'z'); //creates a 3x3x3x3 matrix
                                           //filled with 'z's
tstenner

Turns out, std::vector has a constructor, that constructs a vector with a constant value repeated n times, so a possible solution looks like this:

const int n=2, size=4; //# of dimensions and size of one dimension
boost::multi_array<char,n> arr(std::vector<size_t>(n,size));

This initializes a n-dimensional multi_array with each dimension's size set to size.

From the Boost Multi-Array documentation, yes, you can initialize it one line:

typedef boost::multi_array<double, 3> array_type;
typedef array_type::index index;
array_type A(boost::extents[3][4][2]);

The typedefs are for readability, one can just as easily do for your example:

boost::multi_array<int, 2> arr(boost::extents[2][4]);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!