簡體   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