I am trying to take in an input for the dimensions of a 2D matrix. And then use user input to fill in this matrix. The way I tried doing this is via vectors (vectors of vectors). But I have encountered some errors whenever I try to read in data and append it to the matrix.
//cin>>CC; cin>>RR; already done vector<vector<int> > matrix; for(int i = 0; i<RR; i++) { for(int j = 0; j<CC; j++) { cout<<"Enter the number for Matrix 1"; cin>>matrix[i][j]; } }
Whenever I try to do this, it gives me a subscript out of range error. Any advice?
In fact a vector is also a matrix! Because a matrix can have just one row or one column.
Yes! Yes, you can make a vector of vectors in C++. The normal vector is a one-dimensional list data structure. A vector of vectors is a two-dimensional list data structure, from two normal vectors.
2D vectors are often treated as a matrix with “rows” and “columns” inside it. Under the hood they are actually elements of the 2D vector. We first declare an integer variable named “row” and then an array named “column” which is going to hold the value of the size of each row.
You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:
// assumes using std::vector for brevity vector<vector<int>> matrix(RR, vector<int>(CC));
This creates a vector of RR
size CC
vectors, filled with 0
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With