Emplace an aggregate in std::vector

后端 未结 3 1074
孤街浪徒
孤街浪徒 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:23

    std::vector::emplace expects an iterator as argument too, because it inserts the element before that iterator's position. If you just want to append elements to the vector, use emplace_back. Another problem is that the { i,0.0,0.0,1 } thing is an initializer list, not Particle. If you want to instantiate the Particle struct, then you need to tell the compiler so: Particle{ i, 0.0, 0.0, 1 }. edit: That's because emplace_back expects arguments to later construct the Particle struct, so your attempt won't work as the argument itself will be deduced as an initializer list.

    On the other hand, std::vector::push_back's parameter in this case is of type Particle, so here you're able to pass that init-list, since constructing objects like that is called aggregate initialization (i.e. Particle p = {i, 0.0, 0.0, 1} is valid).

    Final code:

    for (int i = 0; i < num_particles; i++)
    {
        particles.push_back({i, 0.0, 0.0, 1});
    }
    

提交回复
热议问题