user2205449
user2205449

Reputation: 33

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?

Upvotes: 2

Views: 1432

Answers (1)

Pubby
Pubby

Reputation: 53047

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.

Upvotes: 5

Related Questions