编写二维数组的不同方法 [英] different ways to write a 2-d array

查看:62
本文介绍了编写二维数组的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



是否可以用不同于array [i] [j]的语法编写二维数组?

示例:如果我有数组[4] [4],是否可以键入数组[16]而不是通常的方式?是否被视为二维数组?

解决方案

引用:

例子:如果我有数组[4] [4],是否可以输入数组[16]而不是通常的方式?

是的,它是可能的。





引用:

它被认为是一个二维数组?

不,但(即你的代码)可能会认为它是一个二维数组,例如

  #define ROWS 4 
#define COLS 4
int x [ROWS * COLS];
int r,c;
for (r = 0 ; r< ROWS; ++ r)
{
for (c = 0 ; c< COLS; ++ c)
{
int index = r * COLS + c;
x [index] = r == c? 1 0 ;
}
}





上面的代码使用数组 x 作为4x4矩阵,为其分配单位矩阵组件。


是......但是......这不一定是个好主意。

从本质上讲,所有内存只是RAM的块,我们在代码中放置的各种结构最终会映射到那些块。

所以虽然

  int  arr2p [ 4 ] [ 4 ]; 





  int  arr1p [ 16 ]; 



可能会占用相同数量的内存,第二个不是2D数组,虽然(如图所示的CPalini)可以以类似的方式访问它。



但这不是个好主意。部分原因是代码对于下一个必须修改它的人来说不太明显,部分原因是编译器在优化阵列访问代码方面可能比你更好! :笑:

并且...有些系统可以进行边界检查,以确保您不会错误地在2D阵列中连续运行一行,这必须是手动的在作为2D处理的1D数组中完成。



通常,如果需要2D数组,请将其声明为2D数组,以便代码更易于维护。如果出于性能原因需要从一行的末尾运行到下一行的开头,那么无论如何都要使用指针而不是索引。


hi,
is it possible to write 2-d array in a different syntax other than array[i][j]?
example: if i have array[4][4], is it possible to type array[16] instead of the usual way? is it considered as a 2-d array?

解决方案

Quote:

example: if i have array[4][4], is it possible to type array[16] instead of the usual way?

Yes , it is possible.


Quote:

is it considered as a 2-d array?

Nope, however you (that is your code) may consider it as a 2-d array, e.g.

#define ROWS  4
#define COLS  4
int x[ROWS * COLS];
int r,c;
for (r = 0; r < ROWS; ++r)
{
  for( c = 0; c < COLS; ++c)
  {
     int index = r * COLS + c;
     x[index] = r == c ? 1 : 0;
  }
}



The above code uses the array x as a 4x4 matrix, assigning it the identity matrix components.


Yes...but...it's not necessarily a good idea.
In essence, all memory is just "chunks" of RAM, and the various structures we put in our code are ultimately "mapped" to those chunks.
So while

int arr2p[4][4];


and

int arr1p[16];


Will probably occupy the same amount of memory, the second is not a 2D array, although (as CPalini as shown) it can be accessed in a similar way.

But it's not a good idea. Partly because the code is a lot less obvious to the next person to have to modify it, and partly because the compiler is probably a lot better at optimising the code for the array access than you are! :laugh:
And...some systems can do bounds checking to ensure that you don't "run off the end" of a row in a 2D array by mistake, which would have to be manually done in a 1D array treated as a 2D.

Generally, if you need a 2D array, declare it as a 2D array so that the code is more maintainable. If you need to "run" from the end of one row to the beginning of the next for performance reasons, then use pointers instead of indexes anyway.


这篇关于编写二维数组的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆