How to define a 2D array in C++ and STL without memory manipulation?

In C++11 use std::array:

  std::array<std::array<int,3>,2> a {{
    {{1,2,3}},
    {{4,5,6}}
 }};

Some usage:

  a[0][2] = 13;

A common pattern is encapsulating the 2D array inside a class that offers the appropriate interface. In that case, you can use other internal representations, like for example a single vector of rows*cols elements. The interface (usually operator()(int,int) will map the coordinates from the caller to a position in the linear vector.

The advantage is that it has dynamic allocation, but a single allocation (unlike the std::vector<std::vector<int>> where each vector must acquire it's own memory) and in a single block providing locality of data.


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;