[問題] range for with multidimensional arrays

看板C_and_CPP作者 (woody)時間8年前 (2017/04/20 18:18), 8年前編輯推噓1(107)
留言8則, 2人參與, 最新討論串1/1
目前正在讀 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
ia 的形態是 int[3][4], 或曰「長度為 3 的 int[4] 陣列」
04/20 21:36, 1F

04/20 21:36, , 2F
也就是其元素形態是 int[4], 根據規則一個如此形態的值
04/20 21:36, 2F

04/20 21:36, , 3F
會 decay 成指向其首元素的指標, 這就是文中在講的那個
04/20 21:36, 3F

04/20 21:37, , 4F
也就是說, 第一個 auto 會被推斷為 int[4] 然後發生 decay
04/20 21:37, 4F

04/20 21:37, , 5F
但如果是參考的話, int(&)[4] 是一個對如此陣列的參考
04/20 21:37, 5F

04/20 21:38, , 6F
這樣就不會被 decay 而可以進行內層的 for 了
04/20 21:38, 6F
喔喔喔!! 我懂了,非常感謝 ※ 編輯: woody3724 (219.85.134.2), 04/23/2017 16:34:44

04/27 13:26, , 7F
改成 auto& 就可以是因為這樣就會直接抓參考嗎
04/27 13:26, 7F

04/27 13:28, , 8F
阿 沒事我懂了 int& arr 卡了一下...
04/27 13:28, 8F
文章代碼(AID): #1O-8hdkI (C_and_CPP)