nested range-for loops and arrays of arrays

Greetings

My goal is to use range for loops to print out a two-dimensional array. My problem is I don't know how to specify the type of the loop control variable for the outer loop. If I use the auto keyword as shown below, all works fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main()
{
    int ia[3][4] =
    {
    {0,1,2,3},
    {4,5,6,7},
    {8,9,10,11}
    };

    for( auto &row : ia )
    {
        for( int col : row )
        {
            cout << col << " ";
        }
        cout << "\n";
    }

    return 0;
}


problem is I can't use auto for this exercise, I have to specify the type directly, and the book I have doesn't provide an example of this. I've tried several different possibilities in place of auto, without success. If someone could provide an example, or point me in the right direction, I would be grateful.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <iomanip>

int main()
{
    int ia[3][4] =
    {
        {0,1,2,3},
        {4,5,6,7},
        {8,9,10,11}
    };

    using row_type = int[4] ; // the type of a row is 'array of 4 int'
    typedef int row_type[4] ; // same as above; alternative (old) syntax

    for( const row_type& row : ia )
    {
        for( int v : row ) std::cout << std::setw(3) << v ;
        std::cout << '\n' ;
    }
}
ok that works

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>

using namespace std;

int main()
{
    int ia[3][4] =
    {
    {0,1,2,3},
    {4,5,6,7},
    {8,9,10,11}
    };

    using row_type = int[4];

    for( const row_type &row : ia )
    {
        for( int col : row )
        {
            cout << col << " ";
        }
        cout << "\n";
    }

    return 0;
}


is it possible to do this without using a type alias. I tried using

for( int[4] &row : ia )

but it would not compile.
for( const int (&row) [4] : ia ) // without the parentheses, & binds to the left
ok that works, thanks.
Last edited on
Topic archived. No new replies allowed.