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
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.