user1356695
user1356695

Reputation: 217

Nested for loop - 1D indexing

//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();
               }

    }

If I now would want to convert it in a 1D array how could I calculate the correct indices for the 1D array? For example for i=5 and j=0 it should be at the first posistion etc.

EDIT: Updated the code. I tried to calculate something and store it in a 1d array by calculating its index with i*30+j but this doesnt work.

Upvotes: 4

Views: 3578

Answers (1)

Brady
Brady

Reputation: 10357

Assuming the array was defined as follows:

int a[30][5];

you could index into it like this:

a[i][j]

Or define it as a 1 dimension array as follows:

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

Here is an example program that displays the iterations:

(Notice that there are those who might say I switched the rows and columns, but it doesnt really matter since its iterating contiguously through the array. That is if you think of the rows and columns differently, just switch all occurrences and you should get the same result.)

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

And one more piece of information, if you need to allocate a 2D array dynamically, here's how:

int **a = new int*[30];
for(int i = 0; i < 30; ++i)
{
    a[i] = new int[5];
}

Upvotes: 3

Related Questions