Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

c++ - Emplace an aggregate in std::vector

I tried to initialize the std::vector

std::vector<Particle> particles;

with instances of the simple struct

struct Particle {
    int id;
    double x;
    double y;
    double theta;
    double weight;
};

by using emplace with an initializer list:

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

But I get the error

C2660 "std::vector>::emplace_back": Function doesn't accept one argument

How can I fix that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<Particle> 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<Particle> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...