Search code examples
c++vectorinitializationpush-back

Problems when using repeated push_back() to initialize a vector


Problems using repeated push_back() to initialize a vector

So in my program, I have a struct containing only doubles and double arrays:

struct Particle {
    double x[2];
    double v[2];
    double pressure;
    .......
};

When I initialize one of my vectors like this:

    std::vector<Particle> p_vec(2500);  

Everything works fine, but when I replace that line with:

    std::vector<Particle> p_vec;
    Particle p; 
    for (int i = 0; i < 2500; i++) p_vec.push_back(p);

My program still makes it past the for loop, but crashes later.

Is there a difference that I'm missing between these two methods?


Solution

  • The first is default constructing the elements, meaning their members are initialized to 0.

    The second is copying an uninitialized value, which is undefined behavior.

    Try initializing p properly before you push_back.