Declaring and allocating a 2d array in C++

前端 未结 5 1808
天命终不由人
天命终不由人 2021-01-21 18:01

I am a Fortran user and do not know C++ well enough. I need to make some additions into an existing C++ code. I need to create a 2d matrix (say A) of type double whose size (say

5条回答
  •  醉梦人生
    2021-01-21 18:49

    I would recommend using std::vector and avoid all the headache of manually allocating and deallocating memory.

    Here's an example program:

    #include 
    #include 
    
    typedef std::vector Row;
    typedef std::vector Matrix;
    
    void testMatrix(int M, int N)
    {
       // Create a row with all elements set to 0.0
       Row row(N, 0.0);
    
       // Create a matrix with all elements set to 0.0
       Matrix matrix(M, row);
    
       // Test accessing the matrix.
       for ( int i = 0; i < M; ++i )
       {
          for ( int j = 0; j < N; ++j )
          {
             matrix[i][j] = i+j;
             std::cout << matrix[i][j] << " ";
          }
          std::cout << std::endl;
       }
    }
    
    int main()
    {
       testMatrix(10, 20);
    }
    

提交回复
热议问题