Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach loop in 2D Arrays in C++

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?

like image 914
Reza Hajianpour Avatar asked May 12 '13 15:05

Reza Hajianpour


1 Answers

Just use auto keyword

int myArray[3][3];

for(auto& rows: myArray) // Iterating over rows
{
    for(auto& elem: rows)
    {
        // do some stuff
    }
}
like image 169
awesoon Avatar answered Oct 13 '22 21:10

awesoon