I have a 2d array grid made as int GRID[10][20]; What I want to do is remove the last row GRID[LAST][ALL] and insert a blank row at the start of the array. I tried Googleing this with no luck. Thanks
+1
A:
Arrays are static constructs with fixed size. To get the sort of thing you're looking for (indexable contiguous storage with insertion and deletion), you should check out the STL vector container type.
Steve Gilham
2009-09-13 14:08:10
Is is possible to shift the whole array?
Milo
2009-09-13 14:13:15
STL vector would not be optimal for this, he probably wants a queue/deque.
Potatoswatter
2009-09-13 14:29:51
Deque is only piecewise contiguous, so will not be a good match for something that expects to handle arrays.
Steve Gilham
2009-09-13 14:34:30
multi-dimensional arrays are also not contiguous. He never said anything about needing that, anyway.
Potatoswatter
2009-09-13 14:38:23
Worth noting that the other answer is relying on contiguous memory.
Steve Gilham
2009-09-13 18:58:25
Huh? My C++ answers do not rely on contiguous memory. They will work with any container type. It sounds like what he wants is C anyway, which may be the right tool for the job… we don't know.
Potatoswatter
2009-09-13 21:08:23
+3
A:
This is NOT C++, this is C. You can do this:
memmove( GRID[1], GRID, sizeof GRID - sizeof GRID[0] ); // shift the array
bzero( GRID, sizeof GRID[0] ); // zero out the first row
If you were using C++, it would look like this:
GRID.pop_back(); // remove the last row
GRID.push_front( 10 ); // add an initial row
or this (which avoids allocating memory and dependency on size parameters):
rotate( GRID.begin(), GRID.end()-1, GRID.end() ); // shift the array
fill( GRID[0].begin(), GRID[0].end(), 0 ); // zero out the first row
And moreover in C++ you can use a queue instead of a vector, which is what you appear to want. In C++, however, a multi-dimensional array is an array of pointers to arrays, not a C-style array of arrays.
Potatoswatter
2009-09-13 14:28:39