简体   繁体   中英

Access 2D array with 1D iteration

If I define an array as follows:

int rows = 10;
int cols = 10;

double **mat;
mat = new double*[rows];
mat[0] = new double[rows*cols];

for(int r=1; r<10; r++)
    mat[r] = &(mat[0][r*cols]);

How do I iterate over this array via 1-dimension? Eg I'd like to do the following:

mat[10] = 1;

to achieve the same thing as

mat[1][0] = 1;

Is there a way to dereference the double** array to do this?

mat[row * cols + column]

where row is the row you want to access and column is the column you want to access.

Of course an iteration over the array would just involve some kind of loop (best suited would be for ) and just applying the pattern every time.

With your definition of mat , you can do this:

double* v = mat[0]; 'use v a uni-dimensional vector
for(int i =0; i< rows* cols; i++) v[i] = 1;

Alternatively,if what you wanted was to define mat itself as a uni-dimensional vector and use it as bi-dimensional in a tricky way:

double mat[rows * cols];
#define MAT(i, j) mat[i*cols + j]

MAT(1, 0) = 1;
<=>
mat[10] = 1

now you have the options to span the matrix in one-dimension using mat or bi-dimension using the MAT macro

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM