"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)。***スコープの詳細については、こちらをご覧ください。*** ? –
"string"や "Particle"型のオブジェクトの場合、変数名 "name"を再利用していることは別として、このようには動作しないような理由はありません。 「パーティクル」に名前を付けるつもりは、文字列フィールドが設定されていることを意味します。 – jwimberley
すでに言われていることにもかかわらず、「_part0、part1、part2_」という形式の変数を作成する必要がある場合は、配列や同様の構文が必要であることを強く示しています。 –