c++ - Nested for loop - 1D indexing -
//the size of test doesn't matter 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 , store test[i*30+j] = myfunc(); } } if want convert in 1d array how calculate correct indices 1d array? example i=5 , j=0 should @ first posistion etc.
edit: updated code. tried calculate , store in 1d array calculating index i*30+j doesnt work.
assuming array defined follows:
int a[30][5]; you index this:
a[i][j] or define 1 dimension array follows:
int a[30*5]; a[j + 5*i]; here example program displays iterations:
(notice there might switched rows , columns, doesnt matter since iterating contiguously through array. if think of rows , columns differently, switch occurrences , should same result.)
int main(int argc, char **argv) { int columns = 30; int rows = 5; int a[columns*rows]; // not needed example for(int = 0; < columns; ++i) { for(int j = 0; j < rows; ++j) { cout << "[" << << "][" << 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 1 more piece of information, if need allocate 2d array dynamically, here's how:
int **a = new int*[30]; for(int = 0; < 30; ++i) { a[i] = new int[5]; }
Comments
Post a Comment