Insert and remove rows from an int array in c++?
-
07-07-2019 - |
Question
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
Solution
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( std::vector< int >( 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 container (vector
or deque
) is effectively an array of pointers to arrays, i.e. a discontiguous memory structure, unlike a C-style array of arrays which resides in a single memory block.
OTHER TIPS
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.