how to create a contiguous 2d array in c++?

后端 未结 7 1641
走了就别回头了
走了就别回头了 2020-11-21 23:52

I want to create a function that returns a contiguous 2D array in C++.

It is not a problem to create the array using the command:

 int (*v)[cols] = n         


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 00:39

    handling raw memory ressources is often icky. Best shot is a simple wrapper as :

    struct array2D : private std::vector
    {
      typedef  std::vector base_type;
    
      array2D() : base_type(), height_(0), width_(0) {}
      array2D(std::size_t h, std::size_t w) : base_type(h*w), height_(h), width_(w);
    
      int operator()(std::size_t i, std::size_t j) const 
      { 
         return base_type::operator[](i+j*height_); 
      }
    
      int& operator()(std::size_t i, std::size_t j) 
      { 
         return base_type::operator[](i+j*height_); 
      }
    
      std::size_t rows() const { return height_; }
      std::size_t cols() const { return width_; }
    
      private:
      std::size_t height_, width_;
    }
    

    private inheritance let you grab all the goodies from vector, just add your 2D constructor. Ressources management is free as vector ctor/dtor will do their magic. Obviously, the i+h*j can be changed to whateever storage order you want.

    vector< vector< int > > is 2D but won't be contiguous in memory.

    Your function then become :

    array2D create_array(int rows, int cols)
    {
      return array2D(cols,rows);
    }
    

    EDIT:

    You can also retrieve other vector interface parts like begin/end or size with the usign clause to make the private inherited member functions public again.

提交回复
热议问题