nickponline
nickponline

Reputation: 25914

What is the easiest way to convert a Boost MultiArray (2d) to a normal 2d-array?

Is there a best/easiest way of converting a 2D Boost MultiArray to a normal 2D-array other than preallocating and iterating through all the elements?

#include "boost/multi_array.hpp"
#include <cassert>

int main () 
{
  // Create 2D multi-array
  typedef boost::multi_array<double, 2> array_type;
  typedef array_type::index index;
  array_type A(boost::extents[3][4]);

  // Fill in some values ...
  double value = 1.0;
  for(index i = 0; i != 3; ++i) 
    for(index j = 0; j != 4; ++j)
        A[i][j] = value;

  // Convert to a double[3][4]  ...
  double **convert = ???

  return 0;
}

Upvotes: 2

Views: 2460

Answers (1)

SergV
SergV

Reputation: 1277

1) See documentation Boost MultiArray about member function data():

element* data();
const element* data() const;

This returns a pointer to the beginning of the contiguous block that contains the array's data. If all dimensions of the array are 0-indexed and stored in ascending order, this is equivalent to origin(). Note that const_multi_array_ref only provides the const version of this function.

Or

2) You can use multi_array_ref:

multi_array_ref is a multi-dimensional container adaptor. It provides the MultiArray interface over any contiguous block of elements. multi_array_ref exports the same interface as multi_array, with the exception of the constructors.

But in any case - I think it is bad idea to copy data from multi_array to C-array. If the reason is legacy code then see - http://www.boost.org/doc/libs/1_51_0/libs/multi_array/doc/user.html#sec_storage

Upvotes: 1

Related Questions