2014-03-13 80 views
0

我想让我的数组创建与boost功能的工作。我写了下面的代码,但它不工作。 我该怎么做,我的数组被我的函数读取?在此代码的以前版本中,我只是将其定义为双U [N + 1] [4]。它的工作。我在使用boost时做错了什么?如何将Boost multi_array传递给函数?

#include "boost/multi_array.hpp" 
#include <cassert> 
#include <iostream> 
#include <cmath> 
#include <time.h> 

int const N=400; 
int const x1=0; 
int const x2=1; 
int const gammaValue=1.4; 

void Output(double U[N][3]) 
{ 
    double x,dx; 
    dx=(double(x2-x1))/double(N); 
    FILE *fp; 
    double rho,u,p; 
    fp=fopen("result.dat","w+"); 
    fprintf(fp,"%2.30s\n %20.60s\n %20.18s\t %2.3d\t %2.18s\t ","TITLE = \"1D-EULER.dat \"","variables = \"x\", \"rho\", \"u\", \"p\"","zone i=",N+1,"f=point\n"); 


    for(int n=0;n<N+1;n++) 
    { 
     x=x1+n*dx; 
     rho=U[n][0]; 
     u=U[n][1]/U[n][0]; 
     p=(gammaValue-1)*(U[n][2]-0.5*U[n][0]*u*u); 
     fprintf(fp,"%20.5f\t%20.5f\t%20.5f\t%20.5f\n",x,rho,u,p); 
    } 
    fclose(fp); 
} 

int main() { 
    // 3 x 4 x 2 
    typedef boost::multi_array<double, 2> array_type; 
    typedef array_type::index index; 
    array_type A(boost::extents[N][3]); 

    int values = 0; 
    for(index i = 0; i != N; ++i) { 
     for(index j = 0; j != 3; ++j){ 
      A[i][j] = i+j; 
     } 
    } 

    Output(A); 
    return 0; 
} 

回答

2

使用multi_array的成员函数data(),它返回一个指向包含该数组的数据的连续块的开始。一旦获得第一个元素的地址,就可以获得其他元素,因为您已经知道数组的维度。

double * p = A.data(); 
    double (*array)[3] = (double (*)[3])p; 
    Output(array); 
+0

你的意思是输出(A.data()); –

+0

不,你不能,'data()'只返回一个指针。 – jfly

+0

那么你只需要一个转换,如我的答案所示。 – jfly

1

为什么不只是更改输出功能的签名?移动array_type的typedef你的文件的顶部,然后更改输出功能,以这样的:

void Output(array_type& U)

或者,更好,使参数const。这里有一些代码:

#include <boost/multi_array.hpp>                                                    
#include <iostream>                                                       

typedef boost::multi_array< double, 2 > array_type;                                               

void Output(const array_type& arr)                                                   
{                                                            
    std::cout << "here" << std::endl;                                                   
}                                                            

int main(int argc, char ** argv)                                                    
{                                                            
    array_type arr;                                                       
    Output(arr);                                                        
    return 0;                                                         
} 

这没有做任何事情,只是证明适当更改函数签名的原则。

+0

我不确定这是否可行,@RobH,编译器告诉我有一个断言失败, 声明失败:(size_type(idx - index_bases [0])

+0

主体 - 更改类型的参数,使数组可以直接传递 - 是健全的。编译器错误表明你做错了,但我担心。上面我编辑的代码干净地编译。 – RobH