2

this is a follow-up to one of the comments I received for a former question (I gather it's better to ask a new question in these cases).

I created a Matrix class as a vector < vector < double> >, it accepts two integers as inputs (simply, the dimensions of the matrix) and it creates the matrix filled with zeroes.

This is the header:

class Matrix{
public:
/*Basic constructor, accepts matrix dimensions
Matrix(int nr, int nc);
private:
vector<vector<double> > Matrix_;
int nr_, nc_;
};

and the implementation is:

//CONSTRUCTOR
Matrix::Matrix(int nrows, int ncols)
    {
    nc_ = ncols;
    nr_ = nrows;

    /*creates rows*/
    for (int i = 0; i < nrows; i++)
        {
        vector<double> row;
        Matrix_.push_back(row);
        }
    /*Fills matrix with zeroes*/
    for (int i = 0; i < nr_; i++)
        {
        for (int j = 0; j < nc_; j++)
            {
            Matrix_[i].push_back(0);
            }
        }

    }

I have been suggested I can simplify it by using

Matrix::Matrix(int nrows, int ncols) : Matrix_(nrows, std::vector<double>(ncols, 0.)), nr_(nrows), nc_(ncols) {}

Just, I was wondering, mostly out of curiosity...is there any way I could do the same by NOT using the initialization list construct? I am thinking of something like (this is an example, of course this doesn't work)

Matrix::Matrix(int nrows, int ncols):
    {
    Matrix_= vector<vector<double>>(nrows, vector<double>(ncols, 0.));
    nc_ = ncols;
    nr_ = nrows;
    }

Thanks!

Carlo
  • 1,321
  • 12
  • 37

1 Answers1

2

Just remove the :

Matrix::Matrix(int nrows, int ncols) {
    Matrix_ = std::vector<std::vector<double>>(nrows, std::vector<double>(ncols, 0.));
    nc_ = ncols;
    nr_ = nrows;
}

Also note that you don't really need the nr_ as it will be the same value as Matrix_.size()

smac89
  • 39,374
  • 15
  • 132
  • 179