简体   繁体   English

在函数之间传递 boost::multi_array (c++)

[英]Passing boost::multi_array between functions (c++)

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:为此,我使用 boost::multi_array 例如:

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.)现在,由于函数作用域,我显然不能在 printArray() 中使用 myArray,但我也不能直接在类作用域中初始化数组,在函数之外(在两个 typedef 之后)。

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 .要在函数中传递boost::multi_array ,您可以使用像在print引用。 To create a boost::multi_array you must return it as copy.要创建boost::multi_array您必须将其作为副本返回。 The compiler may optimize it to a move.编译器可能会优化它以进行移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM