我想使用基于范围的循环来获取2d矢量的输入.我该怎么办



作为一名初学者,我正在探索多种方法来提高清晰度,所以我做了这个问题。

// no problem with this looping method
vector <vector<int>> vec(n,vector<int>(m));
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> vec[i][j];
}
}
// but i tried in this way using ranged based loop, and it doesn't work. 
// I think i need a few modification here, so i need your help.
for(vector<int> v1d : vec){
for(int x : v1d){
cin >> x;
}
}

同样的代码,只是用cout代替cin,我可以很容易地打印矢量元素。但如果是cin,我就有问题了。没有错误,但它不起作用。

感谢

您需要在循环的范围库中通过引用获取值。否则,v1dx将是副本,您对这些副本所做的任何更改都不会以任何方式影响vec的内容。

for(auto& v1d : vec) {   // or: std::vector<int>& v1d
//      ^
for(auto& x : v1d) { // or: int& x
//          ^
std::cin >> x;
}
}

最新更新