我正在从事与物理引擎相关的项目。在下面的 C++ 代码中:
#include <iostream>
#include <vector>
struct Vector3
{
float x;
float y;
float z;
};
struct object
{
std::vector < std::vector < Vector3 > > set_vertices;
int ID;
int Type;
};
class World
{
public:
std::vector< object > objects;
private:
// other members
};
int main (void)
{
World world;
// How to fill in "objects" of "world"?
// Is this safe to do?
world.objects.resize(5);
// What about the way of allocating "set_vertices" below?
for(size_t i=0; i<world.objects.size(); i++)
{
world.objects[i].set_vertices.resize(12, std::vector < Vector3 >(3));
for(size_t j=0; j<world.objects[i].set_vertices.size(); j++)
{
for(size_t k=0; k<world.objects[i].set_vertices[j].size(); k++)
{
world.objects[i].set_vertices[j][k].x = 0.0f;
world.objects[i].set_vertices[j][k].y = 0.0f;
world.objects[i].set_vertices[j][k].z = 0.0f;
world.objects[i].ID = i;
world.objects[i].Type = 0;
}
}
}
return 0;
}
我为安全分配内存的方式objects
是world
什么?会有任何与内存相关的问题吗?有没有更好的objects
动态初始化方法(即不在构造函数中)?如果是这样,怎么做?谢谢。