我有一个名为“Particle”的结构,我想创建名称取决于int的几个对象。 因为我在for循环中,名称将如下更改:part0,part1,part2。如何在循环内创建名称取决于int的对象
for (int i = 0; i<num_particles; i++)
{
//double sample_x, sample_y, sample_theta;
string name = "part" + std::to_string(i);
Particle name;
name.id = i;
name.x = dist_x(gen);
name.y = dist_y(gen);
name.theta = dist_theta(gen);
cout << "Sample" << " " << name.x << " " << name.y << " " << name.theta << endl;
}
正如你可以想象这种方法不起作用,你有任何解决方案?
我已经更新了我的问题,现在这是我的新方法:
我创建了一个向量和一个int“粒子数”:
std::vector<Particle> particles;
而且功能代码:
void ParticleFilter::init(double x, double y, double theta, double std[]) {
// TODO: Set the number of particles. Initialize all particles to first position (based on estimates of
// x, y, theta and their uncertainties from GPS) and all weights to 1.
// Add random Gaussian noise to each particle.
// NOTE: Consult particle_filter.h for more information about this method (and others in this file).
default_random_engine gen;
normal_distribution<double> dist_x(x, std[0]);
normal_distribution<double> dist_y(y, std[1]);
normal_distribution<double> dist_theta(theta, std[2]);
//for (int i = 0; i<num_particles; i++)
//{
//double sample_x, sample_y, sample_theta;
//string name = "part";
//+ std::to_string(i);
//Particle particles;
particles[num_particles].id =num_particles;
particles[num_particles].x = dist_x(gen);
particles[num_particles].y = dist_y(gen);
particles[num_particles].theta = dist_theta(gen);
num_particles++;
cout << "Sample" << " " << particles[num_particles].x << " " << particles[num_particles].y << " " << particles[num_particles].theta << endl;
//}
}
但它不工作,它输出“分段错误”。
* *为什么你需要在循环内的变量不同的名字呢?在循环中定义的变量是* local *,并且循环中构造的对象将在当前迭代结束时被破坏。也许你需要[得到一些好书](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list),并阅读更多关于***范围*** ? –
除了你正在重用变量名“name”,对于“string”和“Particle”类型的对象,没有理由这样的事情不应该起作用。你打算给“粒子”一个名字的事实意味着它有一个“字符串”字段,你应该设置。 – jwimberley
尽管已经有人说过:如果您需要创建形式为“_part0,part1,part2_”的变量 - 这是一个强烈的迹象表明您需要一个数组或类似的构造。 –