1

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

我如何定义数组以便每个类函数都能够使用它?尺寸在编译时是已知的并且总是相同的。

4

1 回答 1

0

也许你可以使用这个:

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

要在函数中传递 a boost::multi_array,您可以使用 in 之类的引用print。要创建一个boost::multi_array,您必须将其作为副本返回。编译器可能会将其优化为移动。

于 2020-11-23T23:53:26.880 回答