多维数组的目的是什么?多维、目的、数组

2023-09-07 14:26:14 作者:╰╮請陪我迴憶╭╯

我对多维数组的几个问题。我知道如何分配内存的他们,但我不明白为什么有需要(除了让事情变得更易读)。

[] 运营商的阵列过载,对不对?那么,为什么不能一个单独的内存块的分配和访问会批准, 1dArray [I * nInRow] [偏移]

是否有通过使用多个维度的阵列进一步的性能提升?此外,当内存是动态分配的二维数组,都存储在连续的位置,或者他们散落在堆?当请求数据,我可以假设,一切都从内存中作为一个块?

大多数我所看到的资料刚刚解释语法。任何答案或建议的阅读将是巨大的。

解决方案   

[]运算符的阵列过载,对不对?那么,为什么不能一个单独的内存块的分配和访问会批准,1dArray [I * nInRow] [偏移]

是可以的,其实我想在一般情况下,推荐这个。

  

有没有使用数组在多个方面进一步的性能提升?

不是真的。根据您的布局,你可以优化缓存命中,但随后precisely同样是真实的扁平一维数组。两者之间的存储器布局(通常)precisely相同。唯一的区别是语义阵列和事实,你现在必须实现2D元素查找自己的键入的。

  

另外,如果内存是动态分配的二维数组,都存储在连续的位置,或者他们散落在堆?当请求数据,我可以假设,一切都从内存中作为一个块?

数组始终是连续的。

您应该小心,虽然你是的实际上的分配一个二维数组。有些人写的 INT ** PTR =新为int * [2] 然后分配每个子阵手动,认为他们有一个二维数组。他们不。他们有一个指针数组,而这是的,当你得到你的散的布局。你的二维数组是 INT(* PTR)[3] =新的INT [2] [3];

多维数组和矩阵

I have a few questions about multidimensional arrays. I understand how to allocate memory for them, but I don't see why there are needed (Other than to make things more readable).

The [] operator for the array is overloaded, right? So, why can't a single block of memory be allocated and access be granted by, 1dArray[i*nInRow][offset]?

Are there further performance gains by using an array in multiple dimensions? Also, when memory is dynamically allocated for a 2d array, are they stored in contiguous locations, or are they scattered around the heap? When the data is requested, can I assume that everything is pulled from memory as a block?

Most of the information that I have seen has just explained syntax. Any answers or suggested reading would be great.

解决方案

The [] operator for the array is overloaded, right? So, why can't a single block of memory be allocated and access be granted by, 1dArray[i*nInRow][offset]?

It can, and in fact I would recommend this in the general case.

Are there further performance gains by using an array in multiple dimensions?

Not really. Depending on your layout you could optimize cache hits, but then precisely the same is true with the flattened 1D array. The memory layout between the two is (usually) precisely the same. The only difference is the semantic type of the array and the fact that you now have to implement the 2D element lookup yourself.

Also, when memory is dynamically allocated for a 2d array, are they stored in contiguous locations, or are they scattered around the heap? When the data is requested, can I assume that everything is pulled from memory as a block?

Arrays are always contiguous.

You should be careful though that you're actually allocating a 2D array. Some people write int** ptr = new int*[2] then allocate each "sub-array" manually and think that they have a 2D array. They do not. They have an array of pointers, and that's when you get your "scattered" layout. Your 2D array is int (*ptr)[3] = new int[2][3];.