f*****y 发帖数: 1997 | 1 请大家看看我的new和delete用的对么? 传给函数的时候,是传指针还是数组名呢?
void main()
{
double **** g;
g = new double *** [m_ydimension];
for(i=0; i< m_ydimension; i++)
{
g[i] = new double ** [m_xdimension];
for (j=0; j< m_xdimension; j++)
{
g[i][j]= new double * [m_zdimension];
for (k=0; k
{
g[i][j][k] = new double [19];
for (l=0; l<19; l++)
{
g[i][j][k][l]=0.0;
}
}
}
}
ini_pop(double **** g, (int) m_ydimension, (int) m_xdimension, (int) m_
zdimension);
for (i=0;i
{
for (j=0;j
{
for (k=0; k
{
delete [] g[i][j][k];
}
delete [] g[i][j];
}
delete [] g[i];
}
delete [] g;
} | t*******s 发帖数: 7 | 2 超过3维的数组已经反人类了。我会用一个一维的来存贮,
用函数来代替取值。
问题是找值时候是稍微慢点。但是我估计不影响小data size .
我写的代码见下。
最大的好处是可以定义为任意dimensions.
caller 的 interface 不用改变,不用打多余的星星(*),哈哈 | t*******s 发帖数: 7 | 3 #include
#include // malloc ,free
#include //memcpy
typedef double data_t ;
typedef struct {
size_t dims; //number of dimensions
size_t *dim_define; //dim1=10, dim2=10, dim3=20, etc.
data_t *data; //one dimension storage
size_t size ;//size of (data) -optional
}matrix_t ;
matrix_t * matrix_new( size_t dims, size_t *dim_define)
{
size_t i, size=1;
for(i=0; i
size*=dim_define[i];
}
matrix_t *ret=malloc( sizeof(matrix_t));
*ret=(matrix_t){.size=size,
.dims=dims,
.data=malloc(sizeof(data_t)*size),
.dim_define=malloc(sizeof(size_t)*dims ) };
memcpy(ret->dim_define, dim_define, sizeof(size_t)*dims ) ;
return ret;
}
void matrix_free(matrix_t *mat ){
if(mat){
if(mat->data) free(mat->data);
if(mat->dim_define) free(mat->dim_define);
free(mat);
}
}
size_t matrix_get_by_index(matrix_t * mat, size_t * dim_target )
{
size_t i, index=0;
for(i=0;idims; i++){
index+= ( dim_target[i] * mat->dim_define[i] );
}
return index;
}
data_t matrix_get_by_value(matrix_t *mat, size_t *dim_define)
{
size_t index=matrix_get_by_index( mat, dim_define);
return mat->data[index]; //need boundary check
}
void matrix_set_value(matrix_t *mat, size_t *dim_define , data_t value )
{
size_t index=matrix_get_by_index(mat, dim_define);
mat->data[index]=value; //need boundary check
}
int main(){
size_t index;
size_t dims=4;
size_t dim_define[]={ 10,10,10,20};
matrix_t * mat=matrix_new(dims, dim_define);
size_t target[]={2,3,4,5}; //same as data[2][3][4][5]
matrix_set_value( mat, target, 3.14159 );
data_t result=matrix_get_by_value(mat, target) ;
printf("matrix[2][3][4][5] is %f\n", result);
matrix_free(mat);
} | s********i 发帖数: 145 | 4 why not use vector > > >...
Or find a good matrix library
"Always program as if the person who will be maintaining your program is a
violent psychopath that knows where you live" |
|