作為一個初學者,我正在探索多種方法來提高我的清晰度,所以我做了這個問題。
// 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;
}
}
相同的代碼,只是將 cin 替換為 cout,我可以輕松列印該矢量元素。但在 cin 的情況下,我遇到了問題。沒有錯誤,但它不作業。
謝謝
uj5u.com熱心網友回復:
您需要在范圍基礎 for 回圈中通過參考獲取值。否則v1d
,x
將是副本,您對這些副本所做的任何更改都不會vec
以任何方式影響內容。
for(auto& v1d : vec) { // or: std::vector<int>& v1d
// ^
for(auto& x : v1d) { // or: int& x
// ^
std::cin >> x;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506272.html