dimanche 24 février 2019

How C++'s Vector Allocate Memory

Consider my code, I have vector P which type is Particle. Then inside the Particle there's also has vector x, v and xBest.

So, It's vectors inside of vector.

struct Particle
{
    vector<double> x;
    vector<double> v;
    vector<double> xBest;
    double fitness;
    double pBest;
};

class Swarm
{
  public:
    vector<Particle> P;
    Swarm();
};

Since the compiler won't let me reserve memory for vector when declaring a class or struct. like this:

class Swarm
{
  public:
    vector<Particle> P(30);
    Swarm();
};

So, I do it in the constructor like this:

Swarm::Swarm()
{
    P.reserve(30);
    for(size_t i = 0; i < 30; i++)
    {
        P[i].x.reserve(10);
        P[i].v.reserve(10); 
        P[i].xBest.reserve(10);         
    }
}

And it's work.

I'm very curious about this. Since the size of the vectors in struct Particle haven't been initialize yet so the size of Particle is unknown. But I can reserve the memory for 30 Particles even before reserving the memory for 3 vector in struct Particle!!

How is that possible?

Aucun commentaire:

Enregistrer un commentaire