Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: how to initialize the dimensions of a matrix inside a class through parameters of its constructor?

I need help in something really simple, which C++ makes very difficult. I created a class, lattice, with the aim to initialize and treat a matrix. There are the following private members:

private unsigned dim;
private double matrix [dim][dim];

I would like to initialize the variable dim in the constructor of the class through a parameter, but the compiler continue to return errors. I tried to make dim public and static and initializing it in the main program, but there are still problems. How could I create this simple class?

Moreover, I also implemented some methods in the class in order to update the values of the matrix. Is it true that, initializing an object of the class in a main program and then using its "updating" methods, the values of the matrix are stored only once?

Thank you for your help.

like image 448
Pippo Avatar asked Dec 04 '25 18:12

Pippo


1 Answers

There are (at least) three ways to create such a class:

  • with a template

    template<size_t dim>
    class Matrix
    {
       private:
         double matrix[dim][dim];
    }
    
  • with the use of built in types such as std::vector (e.g. valarray would work too)

    #include <vector>
    class Matrix
    {
       private:
         size_t dim;
         std::vector<std::vector<double> > matrix;
       public:
         Matrix(size_t dim_) : dim(dim_), matrix()
         {
           matrix.resize(dim);
           for ( size_t i = 0; i < dim; ++i )
              matrix[i].resize(dim);
         }
    }
    
  • with the use of plain arrays (I do not recommend that!)

    class Matrix
    {
       private:
         size_t dim;
         double** matrix;
       public:
         Matrix(size_t dim_) : dim(dim_), matrix()
         {
           matrix = new double*[dim];
           for ( size_t i = 0; i < dim; ++i )
              matrix[i] = new double[dim];
         }
         ~Matrix() // you need a destructor!
         {
           for ( size_t i = 0; i < dim; ++i )
              delete [] matrix[i];
           delete [] matrix;
         }
    }
    
like image 180
stefan Avatar answered Dec 07 '25 06:12

stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!