[問題] range for with multidimensional arrays

作者: woody3724 (woody)   2017-04-20 18:18:12
目前正在讀 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呢
謝謝
作者: LPH66 (-6.2598534e+18f)   2017-04-20 21:36:00
ia 的形態是 int[3][4], 或曰「長度為 3 的 int[4] 陣列」也就是其元素形態是 int[4], 根據規則一個如此形態的值會 decay 成指向其首元素的指標, 這就是文中在講的那個也就是說, 第一個 auto 會被推斷為 int[4] 然後發生 decay但如果是參考的話, int(&)[4] 是一個對如此陣列的參考這樣就不會被 decay 而可以進行內層的 for 了
作者: hunandy14 (Charlott.HonG)   2017-04-27 13:26:00
改成 auto& 就可以是因為這樣就會直接抓參考嗎阿 沒事我懂了 int& arr 卡了一下...

Links booklink

Contact Us: admin [ a t ] ucptt.com