Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a matrix using STL vector

I want to create a matrix using "vector":

vector < vector <int> > Mat;

The problem is, when I run this code:

int i ,j;
    for(i = 1  ; i <= 5 ; ++i)
    for(j = 1 ; j <= 5 ; ++j)
        Mat[i][j] = 0;

I would get a pretty nasty error. How can I fix that?

I do NOT want to read the matrix like this:

for(i = 1  ; i <= 5 ; ++i)
    for(j = 1 ; j <= 5 ; ++j)
        M[i].push_back(0);
like image 432
ivanciprian Avatar asked Jul 31 '26 15:07

ivanciprian


2 Answers

When you're creating your vectors this way, they have a dimension of 0. You have to initialize them with the good size :

vector < vector <int> > Mat(6, std::vector<int>(6));

By the way, adding a 0 in the second vector initialization will ensure it will be filled with 0 :

vector < vector <int> > Mat(6, std::vector<int>(6, 0));
like image 95
Izukani Avatar answered Aug 02 '26 03:08

Izukani


When you create a vector it starts off empty unless you tell it what the size should be. If the vector is empty then you cannot use [] as it doesn't do any range checking and will not grow the vector. That leaves you with two options, use push_back() or supply a size to the vector when you create it. For instance we could use

const int matrix_size = 5;
auto mat = std::vector<std::vector<int>>(matrix_size, std::vector<int>(matrix_size));
//                                       ^# of rows^                   ^# of cols^

Also remember indexes are 0 based in C++. That means for a vector with 5 elements the valid indexes are [0, 4]. Instead of bothering with the indexes of the vector we can use a ranged based for loop to fill the vector like

for(auto& row : mat)
    for(auto& col : row)
        std::cin >> col;

This will fill every element in the vector from cin.

like image 27
NathanOliver Avatar answered Aug 02 '26 05:08

NathanOliver



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!