This question already has answers here:
Closed 3 years ago.
I am trying to create a class grid
which contains the data members unsigned NR
, unsigned NC
and it should also contain a 2D array double Coordiantes[NR][NC]
. I wish to initialize the data members NR
and NC
through the class constructor. I am trying to avoid the dynamic allocation of the 2-D array as I prefer contiguous memory allocation so as to avoid the cache misses as much as possible.
I am not sure if it is possible but any inputs would be helpful.
class Array2D {
public:
vector<int> v;
int nc;
Array2D(int NR, int NC) : v(NR*NC), nc(NC) {}
int* operator[](int r) { return &v[r*nc]; }
};
int main()
{
Array2D array2d(2, 3);
array2d[0][0] = 1;
array2d[1][2] = 6;
}
This allows you to create a class that will function like a 2D array. It's fast and the data is contiguous.
I recommend you simply use std::vector<double>(NC*NR)
.
And index into it by coord.at(i*NC + j)
(or coord[i*NC + j]
, when you code is correct and you want to glean performance out of it).
You'll get contiguous memory and cache friendly loops without doing your own memory allocation. Always prefer RAII when possible.