c++arraysmultidimensional-arraydynamic-allocation

2d array and 1d array storage comparison?


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.


Solution

  • 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;