Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 () 
{
    /**************
        1   2   3
        4   5   6
    ***************/
    // Method 1
    const int ROW = 2;
    const int COL = 3;
    int array1[ROW][COL];
    for(int i=0; i<ROW; i++)
        for(int j=0; j<COL; j++)
            array1[i][j] = i*COL+j+1;

    // Method 2
    typedef vector<vector<int> > ARRAY; 
    ARRAY array2;
    vector<int> rowvector;
    for(int i=0; i<ROW; i++)
    {
        rowvector.clear();
        for(int j=0; j<COL; j++)
            rowvector.push_back(i*COL+j+1);
        array2.push_back(rowvector);
    }
    return 0;
}

My question is: are there other ways to define the 2D array? Which one is the most efficient one? Thanks!

like image 836
feelfree Avatar asked Oct 11 '12 13:10

feelfree


3 Answers

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;
like image 118
PiotrNycz Avatar answered Sep 18 '22 20:09

PiotrNycz


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.

like image 27
David Rodríguez - dribeas Avatar answered Sep 17 '22 20:09

David Rodríguez - dribeas


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;   
like image 40
Rontogiannis Aristofanis Avatar answered Sep 20 '22 20:09

Rontogiannis Aristofanis