作者woody3724 (woody)
看板C_and_CPP
標題[問題] range for with multidimensional arrays
時間Thu Apr 20 18:18:12 2017
目前正在讀 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://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1492683495.A.B92.html
※ 編輯: woody3724 (219.85.166.154), 04/20/2017 18:27:41
1F:推 LPH66: ia 的形態是 int[3][4], 或曰「長度為 3 的 int[4] 陣列」 04/20 21:36
2F:→ LPH66: 也就是其元素形態是 int[4], 根據規則一個如此形態的值 04/20 21:36
3F:→ LPH66: 會 decay 成指向其首元素的指標, 這就是文中在講的那個 04/20 21:36
4F:→ LPH66: 也就是說, 第一個 auto 會被推斷為 int[4] 然後發生 decay 04/20 21:37
5F:→ LPH66: 但如果是參考的話, int(&)[4] 是一個對如此陣列的參考 04/20 21:37
6F:→ LPH66: 這樣就不會被 decay 而可以進行內層的 for 了 04/20 21:38
喔喔喔!! 我懂了,非常感謝
※ 編輯: woody3724 (219.85.134.2), 04/23/2017 16:34:44
7F:→ hunandy14: 改成 auto& 就可以是因為這樣就會直接抓參考嗎 04/27 13:26
8F:→ hunandy14: 阿 沒事我懂了 int& arr 卡了一下... 04/27 13:28