1

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?

DrVonTrap
  • 33
  • 3
  • 6

4 Answers4

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
  • 1
    Also 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` to avoid memory leaks. Maybe also stuff the whole code into a `class`. – anatolyg Jul 25 '21 at 05:06
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
  • 4
    More 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