在二维矢量中获取用户的输入



我正试图从用户那里获取名为alloc的二维向量中的值,但alloc零索引是唯一更改的索引,每个索引的值都会覆盖它,我不知道为什么(即:只有二维向量的第一个索引受到影响(

代码:

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);不会对temp进行复制,它只是在alloc的末尾添加一个指向temp的指针。在for(i(循环退出之后,temp[及其内容]不再存在。

您需要动态地分配";内部";矢量实例,而不是使用堆栈对象[在这种情况下为temp]。

最新更新