Creating a matrix using STL vector
Solution 1
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));
Solution 2
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
.
Solution 3
vector < vector <int> > Mat;
This creates an empty Mat;
vector < vector <int> > Mat (5);
will create it with 5 "inside" vectors. The problem still isn't solved, you need to resize the interior vectors as well.
you can do this by: (there are plenty of other better ways)
for(int i =0;i<5;i++)
{
Mat[i].resize(5); // resizing the interior matrices
}
Solution 4
It might be better to use std::array。
std::array< std::array<int, 6>, 6> matirx;
for(auto& row: matrix)
for(auto& col: row)
col = 0;
ivanciprian
Updated on June 04, 2022Comments
-
ivanciprian almost 2 years
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);
-
ivanciprian about 8 yearsThanks for the answer, now I understand.
-
NathanOliver about 8 years@epanicafrate No problem
-
Pickle Rick over 4 yearsMuch better in my opinion would be a generic type that accepts any number of dimensions. Whether you have a typical 4x4 or less typical 3x4, it will work the same. You could even set it up to do matrix math on two matrices with different dimensions.