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

后端 未结 7 1501
走了就别回头了
走了就别回头了 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:51

    None of the ways of defining a 2D dynamic array in standard C++ are entirely satisfactory in my opinion.

    You end up having to roll your own solutions. Luckily there is already a solution in Boost. boost::multi_array:

    #include "boost/multi_array.hpp"
    
    template
    boost::multi_array create_array(int rows, int cols) {
      auto dims = boost::extents[rows][cols];
      return boost::multi_array(dims);
    }
    
    int main() {
      auto array = create_array(4, 3);
      array[3][2] = 0;
    }
    

    Live demo.

提交回复
热议问题