0

I have an issue understanding some things about arrays in C++.

If I have array with 3 rows and 4 colomns and I create them as 1d array and accessing each row data by looping through the array by 4 each time . does this way save me time in comparison with 2d approach that take much more allocation.

so instead of this:

int **array = new int * [3];
for(int i = 0; i < 4; i++) {
    array[i] = new int [4];
}

I make this :

int *array = new int [3 * 4];

and I access each row data this way : rows = 3 , colomns = 4 :

for(int i = 0;i < 3; i++) {
    for(int j = 0;j < (3 * 4); j++) {
        cout << "row : << i << " , 4: " array[i * j];
    }
}
  1. does this way save time for my program better than 2d or no?

  2. Is it a bad approach or a good approach writhing my 2d array in 1d array like I what did?

NOTE :

My array will not be dynamic, the size of my array will be know before creating it, I will use it in my neural network project. and my concerns and focus are on speed.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

2 Answers2

0

If your array is not dynamic then there is no difference. Both will be laid out contiguously in memory.

If your array is dynamic then read this answer.

Community
  • 1
  • 1
mpiatek
  • 1,313
  • 15
  • 16
  • nono I will not use it as dynamic I know my size before compling . so In this case both are the same space and performance right ? – ahmed nader Feb 26 '17 at 18:43
0

You may create a Matrix class as follow:

template <typename T, std::size_t R, std::size_t C>
class Matrix
{
public:
    const T& get(std::size_t i, std::size_t j) const { return data[i][j]; }
    T& get(std::size_t i, std::size_t j) { return data[i][j]; }
private:
    T data[R][C] = {};
};

data would be contiguous, and offset computation will be done by compiler.

Usage would be something like:

 Matrix<int, 3, 4> mat;

 mat.get(1, 2) = 42;
Jarod42
  • 203,559
  • 14
  • 181
  • 302