Is it faster to represent at 2D matrix as an array of arrays, or as a 1D array with a function that converts co-ordinates to the corrisponding array index?
            Asked
            
        
        
            Active
            
        
            Viewed 8,116 times
        
    1
            
            
        - 
                    3Benchmark and find out. – James M Oct 28 '14 at 12:10
- 
                    I think that this answers your question http://stackoverflow.com/questions/17259877/1d-or-2d-array-whats-faster – WalkingRandomly Oct 28 '14 at 12:12
- 
                    If the arrays are dynamically allocated, probably the latter. – Neil Kirk Oct 28 '14 at 12:13
- 
                    Two dimensional array!!! – Ali Kazmi Oct 28 '14 at 12:22
4 Answers
4
            
            
        You could make a 1D array and an array of row pointers. Then you get the best of both worlds: a convenient interface with good memory locality and predictable accesses.
int *  matrix1d = new int [rows * cols];
int ** matrix2d = new int * [rows];
for (size_t i = 0; i != rows; ++i)
    matrix2d[i] = &matrix1d[i * cols];
int v1 = matrix1d[r * cols + c];
int v2 = matrix2d[r][c];
 
    
    
        Don Reba
        
- 13,814
- 3
- 48
- 61
- 
                    1Also you can do some cool tricks, like constant-time row swaps (very useful for some matrix reduction algorithms) – Ben Voigt Oct 28 '14 at 12:27
- 
                    Better protect `new` with smart pointers like `vector` or `unique_ptr – anatolyg Jul 25 '21 at 05:06` to avoid memory leaks. Maybe also stuff the whole code into a `class`. 
1
            
            
        I will suggest you to use std::vector because it's dynamic in nature and easy to use.
int row;
int col;
std::vector< std::vector<int> > two_d_matrix( row, std::vector<int>(col));
Note if you are using std::vector don't forget to add #include<vector>.
 
    
    
        Shravan40
        
- 8,922
- 6
- 28
- 48
- 
                    The problem with this approach is that, if you're going to be traversing this thing often, you've just thrown locality of data out the window. – Ed S. Mar 11 '20 at 15:29
0
            
            
        2D array is more convenient, for example
const int rows = 100;
const int cols = 100;
int arr[rows][cols];
You refer the array elements as arr[i][j] where 0 <= i < rowsand 0 <= j < cols
 
    
    
        Dr. Debasish Jana
        
- 6,980
- 4
- 30
- 69
- 
                    4More convenient, until the day when you actually need the size chosen at runtime. Then it falls flat. – Ben Voigt Oct 28 '14 at 12:27
0
            
            
        const int  row = 256;
const int  col = 256;
vector<vector<int> >    matrix2D(row, (col,0));
/*By this we can say that we have a 2D matrix that is 256*256,and all the elements are 0. */
 
    
    
        mark
        
- 11
- 2
