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 (ie: 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();
}
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 [ie temp
in this case].
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.