Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of Vectors to create matrix

Tags:

c++

vector

matrix

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?

like image 968
user1487000 Avatar asked Sep 11 '12 18:09

user1487000


People also ask

Can you write a vector as a matrix?

In fact a vector is also a matrix! Because a matrix can have just one row or one column.

Can you have a vector of vectors?

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.

How do you declare a 2D matrix in a vector C++?

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.


1 Answers

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.

like image 148
juanchopanza Avatar answered Oct 23 '22 07:10

juanchopanza