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

后端 未结 8 1327
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 03:14

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 () 
{
         


        
相关标签:
8条回答
  • 2021-02-06 03:45

    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;   
    
    0 讨论(0)
  • 2021-02-06 03:49

    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)
    
    • Advantages: cache coherency. All the memory is in the same place.
    • Disadvantages: you need a multiply for every indexing. Indirection might be faster.

    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)
    
    • Advantages: indirection may be faster than multiplication.
    • Disadvantages: not cache coherent, since each row is allocated separately (unless the implementation optimizes for vector<vector>).

    If performance is truly important, you need to test both and figure out which is faster on your data.

    0 讨论(0)
提交回复
热议问题