在std :: vector中放置一个聚合 [英] Emplace an aggregate in std::vector

查看:68
本文介绍了在std :: vector中放置一个聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图初始化std :: vector

I tried to initialize the std::vector

std::vector<Particle> particles;

带有简单结构的实例

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

通过将emplace与初始化列表一起使用:

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 });
}

但是我得到了错误

C2660"std :: vector> :: emplace_back":函数不接受一个参数

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

我该如何解决?

推荐答案

std::vector :: emplace 也希望将迭代器作为参数,因为它将元素插入到该迭代器的位置之前.如果仅要将元素添加到向量,请使用 emplace_back .另一个问题是 {i,0.0,0.0,1} 是初始化列表,而不是 Particle .如果要实例化 Particle 结构,则需要告诉编译器: Particle {i,0.0,0.0,1} .这是因为 emplace_back 期望参数稍后再构造 Particle 结构,所以您的尝试将不起作用,因为参数本身将被推导出为初始值设定项列表.

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.

另一方面,在这种情况下, std :: vector :: push_back 的参数的类型为 Particle ,因此在这里您可以传递该init-list,因为构造这样的对象称为聚合初始化(即 Particle p = {i,0.0,0.0,1} 是有效的).

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

最终代码:

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

这篇关于在std :: vector中放置一个聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆