简体   繁体   English

通过一维迭代访问2D数组

[英]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? 有没有办法取消引用double **数组来做到这一点?

mat[row * cols + column]

where row is the row you want to access and column is the column you want to access. 其中row是您要访问的行, column是您要访问的列。

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. 当然,在数组上进行迭代只会涉及某种循环(最适合for ),并且每次都会应用该模式。

With your definition of mat , you can do this: 使用mat的定义,您可以执行以下操作:

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: 或者,如果您想要将mat本身定义为一维向量,并以一种棘手的方式将其用作二维向量:

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 现在,您可以选择使用mat或二维使用MAT宏将矩阵扩展为一维

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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