繁体   English   中英

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

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

假设我需要一个五维数组作为类成员并想在不同的函数中使用它。 为此,我使用 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
}

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

我如何定义数组以便每个类函数都可以使用它? 维度在编译时已知并且始终相同。

也许你可以使用这个:

#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();
}

要在函数中传递boost::multi_array ,您可以使用像在print引用。 要创建boost::multi_array您必须将其作为副本返回。 编译器可能会优化它以进行移动。

暂无
暂无

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

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