在C ++中,这是访问一个二维数组顺序的方式(存储器块明智) [英] In C++, which is the way to access a 2D array sequentially (memory block wise)

查看:128
本文介绍了在C ++中,这是访问一个二维数组顺序的方式(存储器块明智)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:我已经删除了更快/更从问题的标题有效,因为它是misleading..my目的不是优化而是理解阵列。很抱歉的麻烦!

I've removed the faster/more efficient from the question title as it was misleading..my intention was not optimisation but understanding arrays. Sorry for the trouble!

int array[10][10], i, j;

for(i=0;i<10;i++)
{
    for(j=0;j<10;j++)
        std::cin>>array[i][j];
}

对战

int array[10][10], i, j;

for(i=0;i<10;i++)
{
    for(j=0;j<10;j++)
        std::cin>>array[j][i];
}

我是pretty肯定的答案有怎样的阵列在硬件层面实施做;该[] []语法只是一个程序员的抽象,以帮助可视化/建模。不过,我忘了这上面code从开始访问内存块的顺序,直到年底...

I'm pretty sure the answer has to do with how arrays are implemented on a hardware level; that the [ ][ ] syntax is just a programmer's abstraction to aid visualisation/modelling. However, I forgot which of the above code accesses the memory block sequentially from start till end...

感谢所有的答案......

Thanks for all the answers...

只是为了确认我的理解,这是否意味着首code相当于

Just to confirm my understanding, does this mean the first code is equivalent to

int array[10][10], k;

for(k=0;k<100;k++)
{
    std::cin>>*(array+k);
}


推荐答案

除了事实等待获取用户输入将signifficantly比数组存取要慢,第一个比较快。

Aside from the fact that waiting on getting user input will be signifficantly slower than the array access, the first one is faster.

查看二维数组的内存布局此页如果你想了解某个主题的背景。

Check out this page on 2D array memory layout if you want more background on the subject.

使用正在检查的第二个 A [0],A [10] ... A [1],A [11]。

With the second one you are checking A[0], A[10] ... A[1], A[11].

第一顺序将 A [0],A [1],A [2] ..

这篇关于在C ++中,这是访问一个二维数组顺序的方式(存储器块明智)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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