I am trying to understand range based for loops in multidimensional arrays. auto works as a type, but int does not. I was thinking that maybe row is an array, but substituting it didn't work.
Edit:
Actually I think in my substitution I just missed placing a parenthesee, though I still don't understand how to print out the contents of the array if I am using another array to loop through it.
auto& row : type of row is 'reference to array of 3 int'
(Since an array is not a copyable type, it can't be a value.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main()
{
using inner_array_type = int[3] ; // 'inner_array_type' is an alias for 'array of 3 int'
int arr[2][3] = { { 2, 3, 4 }, { 5, 6, 7} };
// same as: */ inner_array_type arr[2] = { { 2, 3, 4 }, { 5, 6, 7} };
// with type deduction
for( auto& row : arr ) // type of row is 'reference to int[3]'
for( auto& col : row) col = 7 ;
// without type deduction
for( inner_array_type& row : arr ) // type of row is 'reference to int[3]'
for( int& col : row) col = 7 ;
// verbose version without type deduction
for( int (&row) [3] : arr ) // type of row is 'reference to int[3]'
for( int& col : row) col = 7 ;
}
Thanks.
What does col = 7 do then? Isn't it basically the index for the row array? How might I use a range based for to change the values in a multidimensional array? I am used to having specific access to the incrementing index variables, but by making row an array, I am confused on how to do it.
This code is my failed attempt at trying to understand how to both use the array index to refer to the individual elements as well as show what those elements are. If I understand both of these things, I think I will have what I need to know.
#include <iostream>
int main()
{
double arr[2][3] = { { 2.3, 3.4, 4.6 }, { 5.7, 6.7, 7.8 } };
constauto print = [&arr] // print the array arr
{
for( constauto& row : arr ) // for each row in the array
{
// print out the values in the row
for( double value : row ) std::cout << value << " " ;
std::cout << '\n' ;
}
std::cout << "-----------------\n" ;
};
print() ;
for( auto& row : arr ) // for each row in the array
for( auto& value : row ) // for each value in the row
value += 1.1 ; // add 1.1 to the value
print() ;
for( auto& row : arr ) // for each row in the array
for( auto& value : row ) value = -98.7 ; // assign -98.7 to the each value in the row
print() ;
}