How do you dynamically allocate a matrix?

前端 未结 11 996
轻奢々
轻奢々 2020-11-29 01:29

How do you dynamically allocate a 2D matrix in C++? I have tried based on what I already know:

#include 

int main(){
    int rows;
    int c         


        
11条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 01:58

    Here is the most clear & intuitive way i know to allocate a dynamic 2d array in C++. Templated in this example covers all cases.

    template T** matrixAllocate(int rows, int cols, T **M)
    {
        M = new T*[rows];
        for (int i = 0; i < rows; i++){
            M[i] = new T[cols];
        }
        return M;
    }
    
    ... 
    
    int main()
    {
        ...
        int** M1 = matrixAllocate(rows, cols, M1);
        double** M2 = matrixAllocate(rows, cols, M2);
        ...
    }
    

提交回复
热议问题