You can encapsulate the creation of an array in a 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;
If you cannot use auto
, you will have to duplicate the template parameters:
boost::multi_array<char, n> arr = make_regular_matrix<char, n>(size);
The make_regular_matrix
function can be shortened to use std::vector
, as in your answer; I do not know if this implementation will be better. The purpose of the helper function is to hide the creation of an array, but other versions can be written, for example, to initialize 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
Luc touraille
source share