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

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

    Simply use better arrays!

    What I mean by that is you can make your own array class which wraps an array, or use some common libraries with such classes (e.g. boost). This is much more reliable, and likely is easier to reason about that straight-up C++ arrays.

    One reason for this is if your write the function

    void foo( int a[][2] )
    {
        // etc.
    }
    

    you don't actually have as many guarantees on the array as you might think. For example, it is not guaranteed that the second dimension of the array is two elements wide (I could be wrong about this point, as I don't have references on hand, but I'm pretty confident about it). This is because that actual signature for the function is

    void foo( int ** );
    

    This is because arrays degenerate to pointers when used in function declarations (which is why you're sizeof(array) returns 4, since 4 bytes is the size of a pointer type on your machine). Also, you clearly have no guarantee on the size of the first dimension, so assuming it is going to be 3 is dangerous, and potentially the result of confusing bugs in the future.

    This is where a custom array class would be great, especially if it were templated. For example, a two dimensional array class could be declared like

    template
    class Array2D
    {
        // Array2D's gutsy stuff to make it act kind of like T[length1][length2]
    };
    

    Using such an approach allows you to maintain all the information about the array in any situation, e.g.

    void foo( Array2D &array ) {}
    

    Now you can decide the sizes every dimension in the array.

    An added benefit, is that you can add bounds checking to your Array2D class, which C++ array do not have. E.g. in a 3x2 array, you are able to access the fourth element in the first row, even though it's not conceptually valid. Such a common source of bugs can easily be eradicated by using an array class like Array2D.

    There are some drawbacks, which is normal when using templates. The big one is that, because of the way template are instantiated, you have to define any templated classes in your header files, not in separate source files (technically, you can use the "export" keyword to do split the class up as normal, but this has limited support on major compilers).

    As a last note (if you're interested, as I am), the situation becomes even better in C++0x (comming soon!) with the advent of variadic templates:

    template
    class Array
    {
        // etc...
    };
    

    Now all array types can be defined by a single class template. Never been easier.

提交回复
热议问题