[問題] range for with multidimensional arrays
目前正在讀 C++ Primer 5th edition
int ia[3][4] = {{0,1,2,3},{4,5,6,7},{8,9,10,11}};
for(auto row : ia)
for(auto col : row)
cout<< col <<endl;
這樣子compile是不會過的
外層迴圈的row必須要是reference才行,也就是 &row
書上的理由如下:
Because row is not a reference, when the compiler initializes row it will
convert each array element (like any other object of array type) to a pointer
to that array's first element. As a result, in this loop the type of row is
int*, The inner for loop is illegal. Despite our intentions, that loop
attempts to iterate over an int* .
reference不就是讓一個變數有了另一個名稱,並且這兩個名稱都使用同一塊記憶體
位址嗎?
為甚麼有reference的話,each array element就不會被轉換成指向第一個元素的指標?
請問為什麼row要reference呢
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.85.166.154
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1492683495.A.B92.html
※ 編輯: woody3724 (219.85.166.154), 04/20/2017 18:27:41
推
04/20 21:36, , 1F
04/20 21:36, 1F
→
04/20 21:36, , 2F
04/20 21:36, 2F
→
04/20 21:36, , 3F
04/20 21:36, 3F
→
04/20 21:37, , 4F
04/20 21:37, 4F
→
04/20 21:37, , 5F
04/20 21:37, 5F
→
04/20 21:38, , 6F
04/20 21:38, 6F
喔喔喔!! 我懂了,非常感謝
※ 編輯: woody3724 (219.85.134.2), 04/23/2017 16:34:44
→
04/27 13:26, , 7F
04/27 13:26, 7F
→
04/27 13:28, , 8F
04/27 13:28, 8F