Emplace an aggregate in std::vector

后端 未结 3 1084
孤街浪徒
孤街浪徒 2020-12-06 03:16

I tried to initialize the std::vector

std::vector particles;

with instances of the simple struct

struct P         


        
3条回答
  •  暖寄归人
    2020-12-06 03:32

    You have several issues with your code:

    • Emplace takes an iterator as insertion point, and then a list of values which serve as arguments to a constructor.

    • Your struct must have a constructor which takes the values you pass to emplace.

    • You only have 4 argument values in your code, but your Particle struct has 5 fields.

    Try this code instead:

    struct Particle {
        int id;
        double x;
        double y;
        double theta;
        double weight;
    
        Particle(int id, double x, double y, double theta, double weight) 
            : id(id), x(x), y(y), theta(theta), weight(weight)
        {
        }
    };
    

    Notice the constructor there. And then emplace, for instance in the beginning [just an example which is not inserting at the back (see below)]:

    std::vector particles;
    
    auto num_particles = 1000;
    for (int i = 0; i < num_particles; i++)
    {
        particles.emplace(particles.begin(), i, 0.0, 0.0, 1.0, 0.0);
    }
    

    As others have noted, if you just want to insert without specifying a specific position in the vector, you can use emplace_back:

    std::vector particles;
    
    auto num_particles = 1000;
    for (int i = 0; i < num_particles; i++)
    {
        particles.emplace_back(i, 0.0, 0.0, 1.0, 0.0);
    }
    

    This inserts the elements at the end of the vector.

提交回复
热议问题