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
    }
}
Share:
15,095
Reza Hajianpour
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, 2022

Comments

  • Reza Hajianpour
    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
    mwerschy about 11 years
    Wont that make i an int* though?
  • awesoon
    awesoon about 11 years
    @MohammadRezaHajianpour, auto keyword is a C++11 feature, yes(like range-based for loop)
  • awesoon
    awesoon about 11 years
    @mwerschy, it this case, rows will be deduced as int (&)[3].
  • mwerschy
    mwerschy about 11 years
    I 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
    Daniël van den Berg over 3 years
    This does not compile, and won't. for ( : ) won't work with an int*.
  • Daniël van den Berg
    Daniël van den Berg over 3 years
    As a note, generally don't use using namespace std nor cout << endl; stackoverflow.com/questions/1452721/… stackoverflow.com/questions/213907/stdendl-vs-n