我有一个带有结构对象 'Particle' 的 C++ 脚本,其中存储了 x、y、z 位置。我创建了几个具有唯一 ID 的粒子对象。如何通过 ID 获取粒子的位置?类似于:particle.getPosByID(int ID);
我的代码如下:
struct Particle {
Vector position { 0.0f, 0.0f, 0.0f };
Vector velocity { 0.0f, 0.0f, 0.0f };
Vector acceleration { 0.0f, 0.0f, 0.0f};
Vector color { 1.0f, 0.0f, 0.0f }; // RED
int ID = 0;}
我在结构中尝试过:
float getPosX(int ID)
{
return this->position.x;
}
使用:float ix = particles->getPosX(5);
但运气不好。有任何想法吗?我需要一个有 getter 的类(class)吗?如果是这样,我该怎么做?到目前为止,Struct 一直很好用并且易于使用...
谢谢!
已编辑
vector 是一个结构:
struct Vector
{
float x, y, z;}
粒子使用数组存储:
const int MaxParticles = 5;
Particle particles[MaxParticles];
最佳答案
Particles are stored using an array
如果粒子 ID 对应于数组索引,则通过 id 访问该数组:
float ix = particles[id].position.x;
如果没有,您可能最好将它们存储在一些关联结构中,例如 map
:
std::map<int, Particle> particles;
然后您可以从结构中删除 id,并使用与上面相同的代码。
关于c++ - 如何通过先前存储的 ID 从结构对象中检索值? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53816629/