如何在循环内创建对象,其名称取决于int

时间:2017-09-24 14:49:24

标签: c++ object struct

我有一个名为“Particle”的结构,我想创建几个名称取决于int的对象。 当我在for循环中时,名称将改变如下:part0,part1,part2。

std::vector<Particle> particles;

你可以想象这种方法不起作用,你有什么解决方案吗?

我已经更新了我的问题,现在这是我的新方法:

我创建了一个向量和一个int“粒子数”:

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;

//}

}

功能代码:

{{1}}

但它还没有工作,它会输出“Segmentation fault”。

3 个答案:

答案 0 :(得分:1)

您可以在代码中使用itoa() cstdlib函数。

for (int i = 0; i<10; i++)
{ 
 char a[max];
 string pa="part_";
string name = pa + itoa(i,a,i+1) ;
cout << "Sample" << " " << name << endl;

}
}

示例输出:

 Sample part_0
 Sample part_1
 Sample part_2
 Sample part_3
 Sample part_4
 Sample part_5
 Sample part_6
 Sample part_7
 Sample part_8
 Sample part_9

答案 1 :(得分:0)

此构造存在于C ++中,称为std::vector

 // we want to have a bunch of variables of type Particle
 // all named particles[i] for i == 0,1,2....
 std::vector<Particle> particles;

 // create a new particle variable
 particles.emplace_back(x, y, theta);

 // print the variable number 42
 std::cout << particles[42];

答案 2 :(得分:-3)

为什么你想要在变量命名的混乱之路上走下去,例如var0var1var2等等?我建议创建一个数组或向量。

从您的代码段中不清楚为什么需要创建具有不同名称的变量。此外,您的代码/用例并不符合变量范围的概念。