Jean-Mathieu Vermosen
Jean-Mathieu Vermosen

Reputation: 107

how to create a mesh of variable dimension in c++?

I would like to design a class which job is to populate a grid of dimension n with n not known at compile time.

Long story short, let's give an example in dimension 1. The class would look like

class grid1D {

public:

    grid1D(double min, double max, double step)
        : min_(min), max_(max), step_(step) {};

    std::vector<double> populate() const 
    {
        std::vector<double> vec;
        for (double i = min_; i < max_; i + step_)
            vec.push_back(i);
        vec.push_back(max_);
        return vec;
    }

private:
    double min_;
    double max_;
    double step_;

}

A straightforward way to generalize this class in (fixed) n dimensions is to nest n for loops. However, if n becomes a parameter, this strategy doesn't work anymore.

I can imagine that creating a large 1D array and trying to populate it "by hand" could be a (tedious) option.

I also checked boost::multi_array class, but ideally, I'd need to define n at runtime.

Any suggestion here ?

Jm

Upvotes: 2

Views: 202

Answers (1)

nullptr
nullptr

Reputation: 11058

One way to do it is to map a N-dimensional grid to a single-dimensional array using a simple formula: element G(x1, x2, ... , xN) is stored in the array at the index x1*NN-1 + x2*NN-2 + ... + xN-1*N + xN, 0<=xi<=N-1 (basically, compiler uses the same formula when you define a multi-dimensional array).

You can easily convert coordinates into the index using Horner's method for calculating the polynom, or index to coordinates using div and mod operations. Thus, iterating over the whole grid is just iterating through all indexes of the single-dimensional array and decoding them into grid coordinates if needed.

Another way would be to implement populate() recursively: N nested loops can be expressed by a single loop inside a recursive function which goes to the depth N. But I think that would be less efficient.

Upvotes: 4

Related Questions