I have a n-dimensional Boost.MultiArray I initialize as follows:
const int n=3, size=4; //# of dimensions and size of one dimension
boost::multi_array
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
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]);
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.