There are several ways to define a 2D array in C++ and STL without memory manipulation, and the following codes illustrate two different methods:
int main ()
{
One very efficient method to define arrays is dynamic allocation, using the new
and delete
operators. Here is an example:
int **arr=new int*[ROW];
for( int i=0; i<ROW; ++i ) {
arr[i] = new int[COL];
for( int j=0; j<COL; ++j ) {
arr[i][j] = some_val;
}
}
The big advantage of this approach is that when you don't need any more the memory that the array uses, you can easily delete it. Here is an example of deleting a 2D array:
for( int i=0; i<ROW; ++i ) {
delete[] arr[i];
}
delete[] arr;
There are a lot of trade-offs here.
If you declare a C-style 2D array int array[height][width]
, then you really get a single contiguous block of memory. The compiler converts indexes to their 1D address
array[row][col] == *(array + row * width + col)
If you use a vector
of vectors
, then each row is allocated separately. The outer vector
stores pointers to the inner vectors
. Indexing becomes an indirection followed by an addition:
array[row][col] == *(*(array + row) + col)
vector<vector>
).If performance is truly important, you need to test both and figure out which is faster on your data.