数组通常如何在底层工作?
他们如何将索引直接映射到值,而无需迭代索引?
如果它相当复杂,我在哪里可以阅读更多内容?
How do they map an index directly to a value without having to iterate though the indices?
If it's quite complex where can I read more?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
数组只是一块连续的内存,从某个已知地址开始。因此,如果起始地址是
p
,并且您想要访问第i
个元素,那么您只需要计算:其中
size
是每个元素的大小(以字节为单位)。粗略地说,访问任意内存地址需要恒定的时间。
An array is just a contiguous chunk of memory, starting at some known address. So if the start address is
p
, and you want to access thei
-th element, then you just need to calculate:where
size
is the size (in bytes) of each element.Crudely speaking, accessing an arbitrary memory address takes constant time.
本质上,计算机内存可以描述为一系列寻址槽。要创建一个数组,您需要留出一个连续的块。因此,如果您的阵列需要 50 个插槽,则可以从内存中预留 50 个插槽。在此示例中,假设您为名为 A 的数组预留了从 1019 到 1068 的插槽。A 中的插槽 0 是内存中的插槽 1019。 A 中的插槽 1 是内存中的插槽 1020。 A 中的插槽 2 是内存中的插槽 1021,依此类推。因此,一般来说,要获取数组中的第 n 个槽,我们只需执行 1019+n 即可。所以我们需要做的就是记住起始槽是什么并适当地添加它。
如果我们想确保不会写入超出数组末尾的内存,我们可能还想存储 A 的长度并根据它检查 n 。还有一种情况是,并非我们希望跟踪的所有值都具有相同的大小,因此我们可能有一个数组,其中数组中的每个项目占用多个槽。在这种情况下,如果 s 是每个项目的大小,那么我们需要预留 s 乘以数组中的项目数,并且当我们获取第 n 个项目时,我们需要在开头添加 s 时间 n 而不仅仅是 n 。但在实践中,这很容易处理。唯一的限制是数组中的每个项目的大小相同。
Essentially, computer memory can be described as a series of addressed slots. To make an array, you set aside a continuous block of those. So, if you need fifty slots in your array, you set aside 50 slots from memory. In this example, let's say you set aside the slots from 1019 through 1068 for an array called A. Slot 0 in A is slot 1019 in memory. Slot 1 in A is slot 1020 in memory. Slot 2 in A is slot 1021 in memory, and so forth. So, in general, to get the nth slot in an array we would just do 1019+n. So all we need to do is to remember what the starting slot is and add to it appropriately.
If we want to make sure that we don't write to memory beyond the end of our array, we may also want to store the length of A and check our n against it. It's also the case that not all values we wish to keep track of are the same size, so we may have an array where each item in the array takes up more than one slot. In that case, if s is the size of each item, then we need to set aside s times the number of items in the array and when we fetch the nth item, we need to add s time n to the start rather than just n. But in practice, this is pretty easy to handle. The only restriction is that each item in the array be the same size.
维基百科对此解释得很好:
http://en.wikipedia.org/wiki/Array_data_struct
基本上,选择一个内存基础。然后将索引添加到基数中。像这样:
二维数组乘以这种效果,像这样:
如果每个索引的大小不同,则需要更多计算:
因此,在这种情况下,几乎不可能不进行迭代而直接映射。
Wikipedia explains this very well:
http://en.wikipedia.org/wiki/Array_data_structure
Basically, a memory base is chosen. Then the index is added to the base. Like so:
Two-dimensional arrays multiply this effect, like so:
And if every index is of a different size, more calculation is necessary:
So, in this case, it is almost impossible to map directly without iteration.