Abstract
Abstract

Reputation: 1005

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? E.g. 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?

Upvotes: 0

Views: 268

Answers (2)

qwertz
qwertz

Reputation: 14792

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.

Upvotes: 1

A.S.H
A.S.H

Reputation: 29332

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

Upvotes: 1

Related Questions