My program crash

I dont know what is happenings with my program, I have tryed to make a program fo create a matrix, with the same number of colums and rows,for that I have used this vector<vector<int> >...my program compile fine, but when I introduce the first value in the funcion to get values, the program crashs....can somebody help me?, thanks, Here is my code:

#include <vector>
#include <iostream>
using namespace::std;

void LlenarVector (vector<vector<int> > &a,int b);

int main() {
vector<vector <int> > array2D;
cout<<"Introduce valor de filas y columnas:"<<endl;
int b;
cin>>b;
LlenarVector(array2D,b);
return 0;
}



void LlenarVector(vector<vector<int> > &a,int b){
int buffer;
for(int i = 0;i<b;i++){

for(int j = 0;j<b;j++){
cout<<"Introduce valor MATRIZ["<<i<<"]["<<j<<"]"<<endl;
cin>> buffer;
a[i][j] = buffer;
}
}

}
Vectors don't automagically resize for you when you use operator[]. You should instead properly use push_back() or resize(). Remember: you have a vector of vectors of ints, not a 2D array.
Thank you, I'll let you know when I do it...
I have managed with that and I made a code which makes so and so what I need...the point is I dont know why I got a matrix with cero values and after my expected matrix...I dont know why....I f you can say something I really would appreciate it, this is my code:

#include <vector>
#include <iostream>
using namespace::std;



typedef vector<vector<int> > matrix;

matrix CopyMatrix(matrix,int);

void ReadMatrix(matrix);

int main(){
int a;
cout<<"size matriz:"<<endl;
cin>> a;
matrix vec(a,vector<int> (a));


vec = CopyMatrix (vec,a);
ReadMatrix(vec);



}



matrix CopyMatrix(matrix vec,int a){

for ( int i = 0; i < a; i++) {
vector<int> row;
for ( int j = 0; j < a; j++) {
int b = 0;
cout<<"Introduce element["<<i<<"]["<<j<<"]:"<<endl;
cin>> b;
row.push_back(b);
}
vec.push_back(row);
}

return vec;

}

void ReadMatrix(const matrix vec){


for( unsigned int i = 0;i <vec.size();i++){
for (unsigned int j = 0; j < vec[i].size(); j++) {

cout<<vec[i][j]<<" ";

}
cout<<endl;
}


}
[code]"Please use code tags"[/code]

1
2
3
4
5
6
7
8
   matrix vec(a,vector<int> (a)); //this would create a matrix of size {a,a} filled with 0
   vec = CopyMatrix (vec,a); 

matrix CopyMatrix(matrix vec,int a){
//...
   vec.push_back(row); //this would append one row, increasing the size of the matrix to {2*a,a} (at the end of the function)
//...
}



PS: in general, the orders are for the program. So you'll say `program show the matrix to the screen' or `program read the input from the user'
Last edited on
Topic archived. No new replies allowed.