take input from user in 2d vector

I am trying to take values in a 2d vector called alloc from the user but the alloc zero index is the only changed index and the values of each index override it i don't know why (i.e: only the first index of the 2d vector is affected)

Code:

cout<<"Please Enter n"<<endl;
cin>>n;
cout<<"Please Enter m"<<endl;
cin>>m;


std::vector<vector<int>> alloc ;
int val;
cout<<"Please Enter values of allocation matrix"<<endl;
for(int i=0;i<n;i++){
vector <int> temp;
for(int j=0;j<m;j++){

cin>>val;
temp.push_back(val);
}
alloc.push_back(temp);
temp.clear();
}

1 answer

  • answered 2021-05-15 15:28 Kevin

    for(int i=0;i<n;i++) {
      vector <int> temp;
      for(int j=0;j<m;j++) {
        cin>>val;
        temp.push_back(val);
      }
      alloc.push_back(temp);
      temp.clear();
    }
    

    alloc.push_back(temp); doesn't make a copy of temp, it merely adds a pointer to temp to the end of alloc. temp [and its contents] ceases to exist after the for(i) loop exits.

    You need to dynamically allocate the "inside" vector instances instead of using a stack object [i.e. temp in this case].