How do you dynamically allocate a matrix?

前端 未结 11 960
轻奢々
轻奢々 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:37

    arr = new int[cols*rows];
    

    If you either don't mind syntax

    arr[row * cols + col] = Aij;
    

    or use operator[] overaloading somewhere. This may be more cache-friendly than array of arrays, or may be not, more probably you shouldn't care about it. I just want to point out that a) array of arrays is not only solution, b) some operations are more easier to implement if matrix located in one block of memory. E.g.

    for(int i=0;i < rows*cols;++i)
       matrix[i]=someOtherMatrix[i];
    

    one line shorter than

    for(int r=0;i < rows;++r)
      for(int c=0;i < cols;++s)
         matrix[r][c]=someOtherMatrix[r][c];
    

    though adding rows to such matrix is more painful

提交回复
热议问题