C++: getting the row size of a multidimensional array passed to a function

后端 未结 6 650
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 03:26

I\'m trying to write a function that will print out the contents of a multidimensional array. I know the size of the columns, but not the size of the rows.

EDIT: Sin

6条回答
  •  悲&欢浪女
    2020-12-11 04:10

    A very simple way to do it, without needing vectors, templates, classes, or passing the size of the array, is to have a last row of data that contains something unique such as the following example, where a -1 is used in the last row, first column:

    #define DATA_WIDTH 7
    
    const float block10g[][DATA_WIDTH] = {
      {0, 15, 25, 50, 75, 100, 125},
      {2.12, 0, 1.000269, 3.000807, 4.24114056, 5.28142032, 6.001614},
      {6.36, 0, 1.2003228, 3.84103296, 6.24167856, 8.16219504, 10.08271152},
      {10.6, 0, 1.2003228, 4.4011836, 7.2019368, 9.2024748, 11.8031742},
      {21.2, 0, 2.000538, 6.001614, 8.002152, 10.4027976, 14.4038736},
      { -1}
    };
    
    
    const float block10g[][DATA_WIDTH] = {
      {0, 20, 50, 100, 150, 200, 250},
      {2.12, 0, 2.88077472, 5.04135576, 5.84157096, 6.08163552, 5.84157096},
      {6.36, 0, 3.84103296, 7.92213048, 11.52309888, 13.56364764, 14.4038736},
      {10.6, 0, 3.8010222, 8.8023672, 13.003497, 16.4044116, 18.4049496},
      {21.2, 0, 4.4011836, 9.2024748, 14.003766, 18.4049496, 22.4060256},
      { -1}
    };
    
    printArrays(block10g,block20g);
    

    Then just break out of the loop(s) when you reach that unique value:

    void printArrays(float array1[][DATA_WIDTH], float array2[][DATA_WIDTH]) {
    
        for (int i = 0; array1[i][0]!=-1 && array2[i][0]!=-1 ; i++) {
            for (int j = 0; j < DATA_WIDTH; j++) {
    
                cout << "\narray1[" << i << "][" << j << "] = "
                     << array1[i][j]
                     << "\tarray2[" << i << "][" << j << "] = "
                      << array2[i][j];
            }
        }
    }
    

提交回复
热议问题