【发布时间】:2017-09-24 14:49:24
【问题描述】:
我有一个名为“Particle”的结构,我想创建几个名称取决于 int 的对象。 由于我在 for 循环中,名称将更改如下:part0、part1、part2。
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;
//}
}
但它还不起作用,它输出“Segmentation fault”。
【问题讨论】:
-
为什么循环内需要不同的变量名称?循环内定义的变量是循环内的local,在循环中构造的对象将在当前迭代结束时被破坏。或许您需要get a couple of good books 并阅读更多关于范围界定的信息?
-
对于“字符串”和“粒子”类型的对象,除了您正在重用变量名称“名称”这一事实之外,没有理由这样的事情不应该工作。您打算给“粒子”起一个名字的事实意味着它有一个“字符串”字段,您应该设置它。
-
尽管已经说过:如果您需要创建形式为“part0, part1, part2”的变量 - 这强烈表明您需要一个数组,或者类似的构造。
-
为什么“粒子编号”不是简单的构造函数参数(如果它对粒子很重要)或者只是容器索引,如果它与粒子无关,只是与管理代码有关。?为什么需要变量名来包含粒子的“
n”? -
使用向量
std::vector<Particle> items(num_particles)(循环前)和循环内访问项目[i]