Reputation: 83
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);
Upvotes: 2
Views: 21315
Reputation: 11
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;
Upvotes: 1
Reputation: 2603
As other answers mention, you need to use the std::vector
constructor with initial numbers of elements to avoid push_back
'ing the elements into the vector later. However if you want to initialize your matrix with zeros, you don't need to specify the default initializer value, because since C++11 the form vector(size_type count)
guarantees zeroing out elements of non-class types such as int
:
vector < vector<int> > Mat( 6, vector<int>(6) );
This creates a 6x6 int matrix with zeros.
Upvotes: 0
Reputation: 8636
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
}
Upvotes: 1
Reputation: 180660
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
.
Upvotes: 2
Reputation: 2612
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));
Upvotes: 7