Size of array object passed to function

后端 未结 4 678
臣服心动
臣服心动 2020-12-22 15:21

I am running the following code in C++:

class Tile {
    //class definition
};

bool myFunction(Tile* Tiles) {
    sizeof(Tiles);
    sizeof(Tiles[0]);
    /         


        
4条回答
  •  伪装坚强ぢ
    2020-12-22 15:59

    The simplest, C-sytle way is to pass the array size as a parameter.

    bool myFunction_ver1(Tile* Tiles, std::size_t size)
    {
        //...
    }
    

    But C++ offers more. Since array size is contained in the data type of the array, a template can help. The array should be passed by reference to prevent the array from being adjusted to pointer.

    template 
    bool myFunction_ver2(const Tile (&Tiles)[N])
    {
        // N is the array size
    }
    

    But we should prefer using std::array or std::vector instead of raw array.

    template 
    bool myFunction_ver3(const std::array& Tiles)
    {
        // You may use N or Tiles.size()
    }
    
    bool myFunction_ver4(const std::vector& Tiles)
    {
        // use Tiles.size()
    }
    

提交回复
热议问题