Search code examples
c++functionmultidimensional-arraylambdaboost-multi-array

(c++) Storing lambda function in a boost multi_array


My plan is to store hundreds (or even thousands) of (interpolation) functions in the multidimensional array multi_array from the boost library. I need to store them, since I need to call them at different points in the project with different numbers as arguments. (I am using the linterp library http://rncarpio.github.io/linterp/ to create the interpolation functions).

I can store the functions in a vector like in the following:

// creating the vector, storing the function
std::vector< std::function< double(double *x) > > interp_list(4);
// storing the function in the vector
interp_list[0] = ( [&] (double *x) { return interp1.interp(x); }  );

However trying the same with a multidimensional array always results in compiling errors:

// creating the array, I want to store the functions in
boost::multi_array< std::function<double (std::vector<double>::iterator)>, 2> interp2_list[2][2];
// storing the function in the vector
interp2_list[0][0] = ( [&] (std::vector<double>::iterator x) { return interp1.interp(x); }  );

I have at least "7 dimensions" for the function (e.g. interp_list[6][2][3][3][64][12][2]) and therefore like to loop over it.

EDIT 1.0: Adding error message:

In file included from /usr/include/boost/multi_array.hpp:26:0, from ./StoreInterp.cpp:16: /usr/include/boost/multi_array/multi_array_ref.hpp: In Instanziierung von »boost::multi_array_ref& boost::multi_array_ref::op erator=(const ConstMultiArray&) [with ConstMultiArray = main()::::iterator)>; T = std::function >)>; long unsigned int NumDims = 2ul]«: /usr/include/boost/multi_array.hpp:371:26: erfordert durch »boost::multi_array& boost::multi_array::o perator=(const ConstMultiArray&) [with ConstMultiArray = main()::::iterator)>; T = std::function >)>; long unsigned int NumDims = 2ul; Allocator = std::allocator >)> >]« ./StoreInterp.cpp:108:22: von hier erfordert /usr/include/boost/multi_array/multi_array_ref.hpp:482:30: Fehler: »const struct main()::::iterator)>« has no member named »num_dimensions« BOOST_ASSERT(other.num_dimensions() == this->num_dimensions());


Solution

  • Your declaration of interp2_list is wrong, your are declaring a 2-D array of boost::multi_array<> with 2 dimensions, so you get a 4-D "thing" with extent 2 for the two first dimension but no extent for the last two dimensions.

    What you actually want is a single boost::multi_array<> initialized with correct dimensions:

    boost::multi_array< std::function<double (std::vector<double>::iterator)>, 2> 
        interp2_list(boost::extents[2][2]);
    

    See boost documentation.