[英]How do I get a view of a boost multi_array and assign it back to the same boost multi_array?
[英]How can I pass a Boost multi_array to a function?
我试图使使用boost创建的数组可以使用一个函数。 我编写了以下代码,但无法正常工作。 我怎样才能使我的函数读取我的数组? 在此代码的先前版本中,我只是将数组定义为double U [N + 1] [4]。 而且有效。 使用Boost时我在做什么错?
#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;
}
使用multi_array的成员函数data()
,它返回一个指针,该指针指向包含数组数据的连续块的开头。 一旦获得第一个元素的地址,就可以得到其他元素,因为您已经知道数组的维数。
double * p = A.data();
double (*array)[3] = (double (*)[3])p;
Output(array);
为什么不只更改Output函数的签名? 将array_type
typedef移到文件顶部,然后将Output函数更改为此:
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;
}
这没有做任何事情,只是演示了适当更改功能签名的原理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.