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

后端 未结 6 652
爱一瞬间的悲伤
爱一瞬间的悲伤 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:18

    You can get the size of both arrays with some template magic:

    template< typename T, std::size_t n, std::size_t m >
    void foo( T(&)[n][m] ) {
      std::cout << n << " " << m << std::endl;
    }     
    
    int main() {
      int a[3][3];
      int b[2][5];
    
      foo(a); foo(b);
    }
    

    This only works for arrays whose bounds are known at compile time and not for dynamically allocated arrays.

    In any case: You should use std::vector or boost::multiarray.

提交回复
热议问题