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();
}
alloc.push_back(temp);
doesn't make a copy oftemp
, it merely adds a pointer totemp
to the end ofalloc
.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].