how initialize 2d vector for user define data i am facing a problem while doing so here is my code
int main() {
int t;
cin>>t;
while(t–){
int N,M,a;
cin>>N>>M;
vector < vector < int >> arr;
for(int i=0;i<N;i++)
{
for(int j =0;j<M;j++){
cin>>a;
arr.push_back(a);
}
}
setZeroes(arr);
cout<<"The Final Matrix is "<<endl;
for (int i = 0; i < arr.size(); i++) {
for (int j = 0; j < arr[0].size(); j++) {
cout << arr[i][j] << " ";
}
cout << “\n”;
}
return 0;
}
I have define this function to find the zero’s element from the ith row and jth col. but what I am doing wrong here plz… can anyone tell ,me what I am mistaking here
Your First doubt :- You can initialize 2-D vectors as :-
vector < vector < int > > your_Vector_Name(row_Size, vector < int > (column_size, your_Data) )
For ex :-
vector < vector < int > > firstVec(20, vector < int > (10, 0) )
will create a 20 x 10 matrix of values 0 assigned.
Your second doubt about the code :- you cann’t push_back an int to a vector<vector>. You have to push_back a vector of int.
So code should look like :-
for(int i=0;i<N;i++)
{
vector<int> tempV;
for(int j =0;j<M;j++){
cin>>a;
tempV.push_back(a);
}
arr.push_back(tempV);
}
1 Like
Thank u for replying i have cried a diffrent way instead of making another vector i took my 2d vector then .initials 2 for looks and what i have dine that my vectors name was arr so i took arr[i][j]=a;
And a is the variables i used to take input from the user is this right approach