Home > Software engineering >  dynamically allocate matrix using build-in vector library
dynamically allocate matrix using build-in vector library

Time:11-03

I am facing problem in allocating matrix using vector library globally. However, in my code, I am allocating vector as an array, which you can see below.

matrix = new double*[row*col];

for (int i = 0; i < row*col; i  ){
    Matrix[i] = new double[col];
}

Please suggest a possible way to allocate matrix globally (preferably using build-in vector or user classes)

matrix = new double*[row*col];

for (int i = 0; i < row*col; i  ){
    Matrix[i] = new double[col];
}

CodePudding user response:

You may use std::vectorlike below:

std::vector<std::vector<double>> matrix(ROW_COUNT, std::vector<double>(COLUMN_COUNT));

Resizing can be done like this:

matrix.resize(new_rows);
for (int i = 0; i < new_rows;   i)
    matrix[i].resize(new_cols);

CodePudding user response:

Normally you would declare matrix as a flat vector:

double matrix[row*col];

But if you want to do it with STL container, I would use @Armin-Montigny sugested:

std::vector<std::vector<double>> matrix;

Of course you could do it as a separate Matrix class, that encapsulates std::vector.

  • Related