Suppose i need a five-dimensional array as class member and want to use it in different functions. For this puropose I use boost::multi_array eg:
class myClass {
typedef boost::multiarray<double, 5> fiveDim;
typedef fiveDim:: index index;
void init(){
fiveDim myArray(boost::extents[3][3][3][3][3]);
// I can use myArray in this scope
}
void printArray(){
// myArray not available here
}
Now, because of the function scope, i can clearly not use myArray in printArray(), but i also can't initialize the array directly in the class scope, outside a function (after the two typedefs.)
How do i define the array so that every class function is able to use it? The dimensions are known at compile time and always the same.
Maybe you can use this:
#include <iostream>
#include <string>
#include <boost/multi_array.hpp>
#include <boost/array.hpp>
#include <boost/cstdlib.hpp>
namespace{
constexpr size_t dim1_size = 3;
constexpr size_t dim2_size = 3;
constexpr size_t dim3_size = 3;
constexpr size_t dim4_size = 3;
constexpr size_t dim5_size = 3;
void print(std::ostream& os, const boost::multi_array<double, 5>& a){
os<<"implementation of print: "<<a[0][0][0][0][0]<<std::endl;
}
boost::multi_array<double, 5> createArray(){
return boost::multi_array<double, 5>(boost::extents[dim1_size][dim2_size][dim3_size][dim4_size][dim5_size]);
}
}
class myClass {
public:
boost::multi_array<double, 5> myArray = createArray();
void printArray(){
print(std::cout, myArray);
}
};
int main()
{
myClass a;
a.myArray[0][0][0][0][0] = 42;
a.printArray();
}
To pass a boost::multi_array
in a function you can use references like in print
. To create a boost::multi_array
you must return it as copy. The compiler may optimize it to a move.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.