C++ 2D array to 1D array

后端 未结 4 1530
春和景丽
春和景丽 2020-12-17 00:23

I am attempting to convert a 2D array to 1D. I\'m extremely new to C/C++ but I think it\'s very important to learn how to convert a 2D array to 1D. So here I am stumbling u

相关标签:
4条回答
  • 2020-12-17 00:58

    http://www.cplusplus.com/doc/tutorial/arrays/

    In that link look at the section on pseudo-multidimensional arrays.

    I've seen many examples that that get the subscripting algorithm wrong. If in doubt, trace it out. The order of sub-scripting a 2D array should go sequentially from 0-(HEIGHT*WIDTH-1)

    #define WIDTH 5
    #define HEIGHT 3
    
    int jimmy [HEIGHT * WIDTH];
    int n,m;
    
    int main ()
    {
      for (n=0; n<HEIGHT; n++)
        for (m=0; m<WIDTH; m++)
        {
          jimmy[n*WIDTH+m]=(n+1)*(m+1);
        }
    }
    
    0 讨论(0)
  • 2020-12-17 01:03

    You are right with your supposition:

    The cycle should be like:

    for (q = 0; q < n; q++)
    {
        for (t = 0; t < m; t++)
        {
            b[q * m + t] = a[q][t];
        }
    }
    

    It is always easier to consider such conversions from the view point of the higher dimension array. Furthermore with your code you did not actually modify i or j in the b assigning cycle, so you should not expect different values to be assigned to the different array members of b.

    0 讨论(0)
  • 2020-12-17 01:04

    First of all, the size of the 1D array should be n*m.

    The cycle can be as follows-

    int lim = n*m;
    
    for(q = 0; q<lim; ++q) {
    
        b[q] = a[q/m][q%m];
    }
    
    0 讨论(0)
  • 2020-12-17 01:07

    This code

    int n=0,m=0; // 2D array nRow, nCol
    int a[n][m];
    

    is invalid. First of all the dimensions shall be constant expressions and there is no sense to set them to 0.

    And the more simple way to do your task is to use pointer. For example

    int *p = b;
    
    for ( const auto &row : a )
    {
        for ( int x : row ) *p++ = x;
    }
    
    0 讨论(0)
提交回复
热议问题