Home > Backend Development > C++ > How Can I Statically Declare a 2D Array as a Class Data Member in C ?

How Can I Statically Declare a 2D Array as a Class Data Member in C ?

Linda Hamilton
Release: 2024-12-11 00:56:12
Original
1014 people have browsed it

How Can I Statically Declare a 2D Array as a Class Data Member in C  ?

Statically Declaring a 2-D Array as a Class Data Member

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template