How do you dynamically allocate a matrix?

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

    You can also use std::vectors for achieving this:

    using std::vector< std::vector >

    Example:

    std::vector< std::vector > a;
    
      //m * n is the size of the matrix
    
        int m = 2, n = 4;
        //Grow rows by m
        a.resize(m);
        for(int i = 0 ; i < m ; ++i)
        {
            //Grow Columns by n
            a[i].resize(n);
        }
        //Now you have matrix m*n with default values
    
        //you can use the Matrix, now
        a[1][0]=1;
        a[1][1]=2;
        a[1][2]=3;
        a[1][3]=4;
    
    //OR
    for(i = 0 ; i < m ; ++i)
    {
        for(int j = 0 ; j < n ; ++j)
        {      //modify matrix
            int x = a[i][j];
        }
    
    }
    

提交回复
热议问题