Your goal is to create a grid class with data members NR, NC, and a 2D array Coordinates[NR][NC]. You want to initialize NR and NC through the class constructor and avoid dynamic memory allocation to optimize memory usage and minimize cache misses.
To achieve this, consider using std::vector, which provides contiguous memory allocation. Here's a modified version of your code snippet:
class grid { public: vector<double> coordinates; unsigned NR, NC; grid(unsigned NR, unsigned NC) : NR(NR), NC(NC), coordinates(NR * NC) {} double& operator()(unsigned r, unsigned c) { return coordinates[r * NC + c]; } }; int main() { grid g(2, 3); g(0, 0) = 1; g(1, 2) = 6; }
This class defines a 2D array using a contiguous vector. The operator() method provides a convenient way to access elements using row and column indices.
This approach avoids dynamic allocation, provides contiguous memory allocation, and ensures efficient memory usage.
The above is the detailed content of How Can I Statically Declare a 2D Array as a Class Data Member in C ?. For more information, please follow other related articles on the PHP Chinese website!