0

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];
}
Arif
  • 11
  • 2
  • 2
    You're creating a matrix with `row*col` rows, and `col` columns. Is that really what you're supposed to do? – Some programmer dude Nov 02 '22 at 13:42
  • I am creating matrix using array format, like in for loop it allocate memory of matrix using array size as a vector.. But, I am looking for the way to allocate matrix using build-in vector i.e. std::vector – Arif Nov 02 '22 at 14:11
  • [Take a look at this trick posted by doug](https://stackoverflow.com/a/36123944/4581301). Resizing the `vector` is more difficult, you have to do all of the copying yourself, but the performance improvements from contiguous memory are usually worth it. – user4581301 Nov 02 '22 at 15:34
  • Does this answer your question? "[Initialize Vector Of Vectors in C++](/q/31200535/90527)", "[Arrays vs Vector of Vectors when creating matrices - what is the most practical option?](/q/62837573/90527)" – outis Nov 02 '22 at 22:06

2 Answers2

2

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);
A M
  • 14,694
  • 5
  • 19
  • 44
  • 1
    Resizing the matrix will not work like this, as only newly created rows will have the correct column count. – DrPepperJo Nov 02 '22 at 13:44
  • 2
    @DrPepperJo. You are right. I updated my answer. – A M Nov 02 '22 at 13:56
  • Thank you, it worked. Now, I want to allocate in header file and outside the main function, so that I won't call matrix in each function. – Arif Nov 03 '22 at 08:33
0

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.

Nikola
  • 125
  • 1
  • 8