I\'m having some issues passing vectors to functions. My concern is not with my logic itself, as if I need to adjust later I will. My program requirements state that I must
You never add the elements to the matrices, ie. matrix
and matrix2
are empty when you call build. You need to size the matrix after your receive the users input.
void build(){
//currently intended just to build 2x matrices of different increasing data
int k=0, l=5;
cout<<"Enter the number of rows for each Matrix: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>col;
matrix.resize(row);
matrix2.resize(row);
for( int i = 0; i < row; i++ ) {
matrix[i].resize(col, 0);
matrix2[i].resize(col, 0);
for ( int j = 0; j < col; j++ ){
matrix[i][j] = k++;
matrix2[i][j] = l++;
}
}
You're not resizing the vectors/matrices to the dimensions that the user put in - they're stuck at row == 0, col == 0 because that's what the two variables default to.
You'd want to look at vector::resize()
to update the dimensions of the vector after the user input.
Your global definitions of row
,col
,matrix
, ... is the problem.
int row=0, col=0;
vector<vector<int> > matrix(row, vector<int> (col) );
vector<vector<int> > matrix2(row, vector<int> (col) );
vector<vector<int> > matrix3(row, vector<int> (col) );
What's happening here is the following: row
and col
is now 0
and therefore all your matrices now have 0 rows and columns.
You can fix this by using the vector::resize()
function after you get row
and col
from the user.
cout<<"Enter the number of rows for each Matrix: "<<endl;
cin>>row;
cout<<"Enter the number of columns for each Matrix: "<<endl;
cin>>col;
// Resize "matrix"
matrix.resize(row);
for(int i = 0; i < row; ++i) matrix[i].resize(col);
// Repeat for "matrix2" and "matrix3"
Also, this means you don't have to "initialize" your matrix
objects. So now you can just define them as:
vector<vector<int> > matrix;
vector<vector<int> > matrix2;
vector<vector<int> > matrix3;
vector
and your printMatrix
and addMatrix
functions can call vector::size()
to find out the size of your matrix. You should rewrite those functions to take your matrix as an argument (lots of good advice here on that) and then work on them.You must use push_back to initialize elements of a vector, or you must size the vectors before using [index]= form.
Matrices are created when row and col are zero, so any attempt to access their contents results in a segmentation fault. You need to first read row and col, and then build the matrices. This excludes making them global variables.
int row=0, col=0;
vector<vector<int> > matrix(row, vector<int> (col) );
vector<vector<int> > matrix2(row, vector<int> (col) );
vector<vector<int> > matrix3(row, vector<int> (col) );
This creates the vectors while row
and col
are still zero, long before you read in the values.