4
//The size of test doesn't matter for now just assume it's fitting
int* test = new int[50000]
    for(int i=stepSize;i<=maxValue;i+=stepSize){

               for(int j=0;j<=i;j+=stepSize){
                    //Comput something and store it
                    test[i*30+j] = myfunc();
               }

    }

如果我现在想将其转换为一维数组,我该如何计算一维数组的正确索引?例如对于 i=5 和 j=0 它应该在第一个位置等。

编辑:更新了代码。我试图计算一些东西并将其存储在一维数组中,方法是用 i*30+j 计算它的索引,但这不起作用。

4

1 回答 1

3

假设数组定义如下:

int a[30][5];

你可以像这样索引它:

a[i][j]

或者将其定义为一维数组,如下所示:

int a[30*5];
a[j + 5*i];

这是一个显示迭代的示例程序:

(请注意,有些人可能会说我切换了行和列,但这并不重要,因为它在数组中连续迭代。也就是说,如果您以不同的方式考虑行和列,只需切换所有出现的位置,您应该得到结果相同。)

int main(int argc, char **argv)
{
    int columns = 30;
    int rows = 5;
    int a[columns*rows]; // not really needed for this example

    for(int i = 0; i < columns; ++i)
    {
        for(int j = 0; j < rows; ++j)
        {
            cout << "[" << i << "][" << j << "] offset: " << (i*rows + j)
                 << endl;
        }
    }
}

[0][0] offset: 0
[0][1] offset: 1
[0][2] offset: 2
[0][3] offset: 3
[0][4] offset: 4
[1][0] offset: 5
[1][1] offset: 6
[1][2] offset: 7
[1][3] offset: 8
[1][4] offset: 9
[2][0] offset: 10
[2][1] offset: 11
[2][2] offset: 12
[2][3] offset: 13
[2][4] offset: 14
[3][0] offset: 15
[3][1] offset: 16
[3][2] offset: 17
[3][3] offset: 18

...

[27][4] offset: 139
[28][0] offset: 140
[28][1] offset: 141
[28][2] offset: 142
[28][3] offset: 143
[28][4] offset: 144
[29][0] offset: 145
[29][1] offset: 146
[29][2] offset: 147
[29][3] offset: 148
[29][4] offset: 149

还有一条信息,如果您需要动态分配二维数组,方法如下:

int **a = new int*[30];
for(int i = 0; i < 30; ++i)
{
    a[i] = new int[5];
}
于 2012-06-05T10:56:36.153 回答