Home >Backend Development >C++ >How Can I Implement Statically Declared 2-D Arrays as Class Data Members in C ?
Statically Declared 2-D Arrays in C as Class Data Members
In C , it is possible to create classes that incorporate statically declared 2-dimensional arrays as data members. This approach differs from dynamic allocation, where memory for the array is dynamically reserved during runtime.
To achieve this, a vector container can be utilized inside the class along with appropriate indexing mechanisms. Here's an example:
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]; } };
In this example, the class contains a vector v and an integer nc representing the number of columns. The constructor is used to initialize the vector with the appropriate size and store the number of columns.
The [] operator is redefined to provide an interface to access the array elements efficiently. When you access array2d[r][c], it internally calculates the index in the vector based on r (row) and c (column). This eliminates the need for separate memory allocation for the array.
Example usage:
Array2D array2d(2, 3); array2d[0][0] = 1; array2d[1][2] = 6;
This method allows you to create a C class that behaves like a 2-D array while maintaining the benefits of contiguous memory allocation, reducing cache misses, and improving performance.
The above is the detailed content of How Can I Implement Statically Declared 2-D Arrays as Class Data Members in C ?. For more information, please follow other related articles on the PHP Chinese website!