多维数组的目的是什么? [英] What is the purpose of multidimensional arrays?

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

问题描述

我有几个关于多维数组的问题.我了解如何为它们分配内存,但我不明白为什么需要(除了使事情更具可读性).

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).

数组的 [] 运算符重载了,对吗?那么,为什么不能通过 1dArray[i*nInRow][offset] 分配单个内存块并授予访问权限?

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.

推荐答案

数组的 [] 运算符已重载,对吗?那么,为什么不能通过 1dArray[i*nInRow][offset] 分配单个内存块并授予访问权限?

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?

数组总是连续的.

尽管您实际上在分配一个二维数组,但您应该小心.有些人写 int** ptr = new int*[2] 然后手动分配每个子数组"并认为他们有一个二维数组.他们不.他们有一个指针数组,那就是当你得到你的分散"布局时.你的二维数组是 int (*ptr)[3] = new int[2][3];.

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];.

这篇关于多维数组的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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