2

I have a function that needs to create a boost multi_array for which the dimensions are not known a priori. However, the extents ARE known for any given dimensionality. How do I incrementally build up an extents object for my array?

Something like:

array_type::extent_gen<array_type::dimensionality> my_extents;
for (size_type d = 0; d < array_type::dimensionality; d++) {
    extents = extents[5];
}
array_type my_array(extents);

Would set an not-yet-determined array to have an extent of 5 in every dimension....

Him
  • 5,257
  • 3
  • 26
  • 83

1 Answers1

0

I don't think you can, since the dimensionality of multi_array is encoded in the type's template arguments:

typedef boost::multi_array<double, 3> array_type;

Is fundamentally distinct from

typedef boost::multi_array<double, 2> array_type;

The "best" you might do is have

static const int MAX_DIMENSIONS = 10;
typedef boost::multi_array<double, MAX_DIMENSIONS> array_type;

And then build the extents to leave the "unused" dimension's extent at 1:

Live On Coliru

#include <boost/multi_array.hpp>
#include <iostream>

static const int MAX_DIMENSIONS = 5;
typedef boost::multi_array<double, MAX_DIMENSIONS> array_type;

array_type make_array(int dims, int default_extent = 5) {
    boost::array<int, MAX_DIMENSIONS> exts = {};
    std::fill_n(exts.begin(), exts.size(), 1);
    std::fill_n(exts.begin(), dims, default_extent);

    return array_type(exts);
}

int main() {
    auto a = make_array(3);
    auto b = make_array(2);

    std::copy(a.shape(), a.shape() + a.dimensionality, std::ostream_iterator<size_t>(std::cout << "\na: ", " "));
    std::copy(b.shape(), b.shape() + b.dimensionality, std::ostream_iterator<size_t>(std::cout << "\nb: ", " "));
}

Prints

a: 5 5 5 1 1 
b: 5 5 1 1 1 
sehe
  • 374,641
  • 47
  • 450
  • 633
  • (Note you can subsequently get an array view from that array that transparently hides the unused dimensions, but - again - you'll get distinct static types there) – sehe Sep 23 '16 at 09:37