2013-10-30 26 views
0

所以我正在做一个任务,我需要首先按行排列数组元素,然后按列排序。我是否正确地为2D数组添加行和列?

我现在有是这样的:

// Sum by Rows 
for(int y =0; y< height; y++) 
{ 
    for(int x = 0; x< width; x++) 
    { 
     total += array2d[x][y]; 
    } 
} 

// Sum by Columns 
for(int x =0; x< width; x++) 
{ 
    for(int y = 0; y< height; y++) 
    { 
     total += array2d[x][y]; 
    } 
} 

这是正确的?我只是想事先确定,因为这似乎太容易成为答案。

+0

看起来不错,如果你要计算总的总和。或者你需要计算每行和存储/输出的总和? –

+0

这个想法是缓存时间我有一个计时器环绕它,显示它执行操作的秒。这些都是在每次迭代后重建阵列的方法都要大得多,因此可以看出缓存时序的差异。 – Darxval

+0

我认为一个好的编译器可以优化它以更好地缓存命中。所以,你使用的没有什么不同。 – deepmax

回答

0

一些修改 -

// Sum by Rows 
for(int y =0; y< height; y++) 
{ 
    for(int x = 0; x< width; x++) 
    { 
    total += array2d[y][x]; // y,x not x,y since you want row(y) to be fix 
          // for each column in that row 
    } 
    //total = 0;  //uncomment this if you want sum for each row (store it or print it) 
} 

更改列的索引也相应