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

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

    Since you're using C++ and not C, I would recommend to use one vector instead of messing around with new/delete.

    You can define one contiguous block of memory like this:

    std::vector my_matrix(rows*cols);
    

    And now you access this vector in a 2d-array-like way with the formula i*n + j, with i being the row index, j the column index and n the length of a row:

    my_matrix[i*n + j];
    

    That's the same as accessing a 2d array with array[i][j]. But now you have the advantage of one contiguous block of memory, you don't need to bother about new/delete and you can easily share and return this vector object with functions.

提交回复
热议问题