As a beginner i am exploring multiple methods to increase my clarity, so i did this question.
// 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;
}
}
Same code, just cin replaced by cout, i can print that vector elements easily. but in case of cin i am having problem. no error, but it's not working.
Thanks
CodePudding user response:
You need to take the values by reference in the range base for-loops. Otherwise v1d
and x
will be copies and any changes you make to those copies will not be affecting the content of vec
in any way.
for(auto& v1d : vec) { // or: std::vector<int>& v1d
// ^
for(auto& x : v1d) { // or: int& x
// ^
std::cin >> x;
}
}