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

后端 未结 7 1499
走了就别回头了
走了就别回头了 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<typename T>
    boost::multi_array<T, 2> create_array(int rows, int cols) {
      auto dims = boost::extents[rows][cols];
      return boost::multi_array<T, 2>(dims);
    }
    
    int main() {
      auto array = create_array<int>(4, 3);
      array[3][2] = 0;
    }
    

    Live demo.

    0 讨论(0)
提交回复
热议问题