foreach loop in 2D Arrays in C++
15,095
Just use auto
keyword
int myArray[3][3];
for(auto& rows: myArray) // Iterating over rows
{
for(auto& elem: rows)
{
// do some stuff
}
}
![Reza Hajianpour](https://i.stack.imgur.com/dUoG4.jpg?s=256&g=1)
Author by
Reza Hajianpour
M.Eng student at Queen's University at Kingston, ON, Canada. I love C++, Javascript, game dev, and natural language processing. I hate Microsoft, Adobe, everything Microsoft-ish. Linux-savvy!
Updated on July 18, 2022Comments
-
Reza Hajianpour almost 2 years
I have a 3x3 2D array. I want to reach to all of it's elements. Is it possible? I do this:
int myArray[3][3]; for(int &i: myArray){ //MY CODE HERE. }
But when I do, I get error:
error: C2440: 'initializing' : cannot convert from 'int [3]' to 'int &'
I also use MSVC++ 2012 compiler on Qt 5.0 x64. And if it's possible to do so, then how can I get the index number of each element?
-
mwerschy about 11 yearsWont that make
i
anint*
though? -
awesoon about 11 years@MohammadRezaHajianpour,
auto
keyword is a C++11 feature, yes(like range-based for loop) -
awesoon about 11 years@mwerschy, it this case,
rows
will be deduced asint (&)[3]
. -
mwerschy about 11 yearsI was talking about what you were doing before you edited ;) Though you are of course right that it wouldn't have been an
int*
. -
Daniël van den Berg over 3 yearsThis does not compile, and won't. for ( : ) won't work with an int*.
-
Daniël van den Berg over 3 yearsAs a note, generally don't use using namespace std nor cout << endl; stackoverflow.com/questions/1452721/… stackoverflow.com/questions/213907/stdendl-vs-n