access 2D array by using single loop

hello! how access a 2D array with just one loop like 1D array and by using pointers too. i read an article on link http://cplusplus.com/forum/articles/17108/ but i didn't understand it. so plz tell me how can i access 2D array according to given situation.
Last edited on
how access a 2D array with just one loop like 1D array


Let's start by saying "you shouldn't".

If you have a 2D array, the whole point is to treat each dimension as a separate thing. Just make 2 loops. It's the easiest, cleanest, safest, and least error prone way to do this.




That said....

If you have a real 2D array, you can ignore the outer bound:

1
2
3
4
int ar[8][10];  // an 8x10 array

for(int i = 0; i < 8*10; ++i)
    ar[0][i] = whatever;


With regular 2D arrays, the arrays are stored back-to-back in memory. So while this will go out of bounds of each individual array, you will stay in bounds of the array-of-arrays.



With "nested new" style arrays (pointer to a pointer, or vector of a vector), you're hosed. You can't do it in one go because the data is not arranged linearly, but instead is scattered around.

You could 'fake' a nested loop with something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
vector<vector<int>> ar(8,vector<int>(10));  // 8*10 vector of vectors

// fake it with 1 loop:
for(int i = 0; i < 8*10; ++i)
{
    auto& inner = ar[i/10];
    inner[i%10] = whatever;
}

// or just do it normal with 2 loops:
for(int y = 0; y < 8; ++y)
{
    for(int x = 0; x < 10; ++x)
        ar[y][x] = whatever;
}
Topic archived. No new replies allowed.