c++vectorinitializationstdarrayconstruct

Replacing old C style arrays with modern C++ STL data structures


I implemented a simple class for n-body simulations in C++. However, the class uses a lot of old C style arrays which I want to replace with data structures that the STL offers.

Here is the relevant part of my code that I want to improve:

struct Particle{
    double m;           // mass
    double x[DIM];      // position
    double v[DIM];      // velocity
    double F[DIM];      // force 
};

class Nbody {
    private:
        const unsigned int n;           // number of particles
        const double dt;                // step size
        const double t_max;             // max simulation time
        std::vector<Particle> p;
    public:
        ~Nbody(){};
        Nbody(unsigned int n_, double dt_, double t_max_);
};

Nbody::Nbody(unsigned int n_, double dt_, double t_max_)
    : n{n_}, dt{dt_}, t_max{t_max_} {
    p = new std::vector<Particle> [n];
}

I tried to use std::vector<Particle>. But how do I in this case initialize n particles correctly? My current approach does not work and the compiler throws many errors. How do I do it correctly?


Solution

  • p is not a pointer. p is declared as a vector.

    Rewrite the constructor definition like

    Nbody::Nbody(unsigned int n_, double dt_, double t_max_)
        : n{n_}, dt{dt_}, t_max{t_max_}, p( n_ ) {
    }
    

    In this case the vector p is initialized as a vector having n elements that are value initialized.

    Also in the definition of the structure Particle you could substitute the arrays to objects of the type std::array<double, DIM>. Also it is better to make the constant DIM either as enumerator of the structure or as a static data member of the structure/