0

我正在从事与物理引擎相关的项目。在下面的 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;
}

我为安全分配内存的方式objectsworld什么?会有任何与内存相关的问题吗?有没有更好的objects动态初始化方法(即不在构造函数中)?如果是这样,怎么做?谢谢。

4

2 回答 2

2

我想使用 RAII 并使用构造函数和析构函数object来处理内存将是一种更好的方法。

添加一个新的object世界,您可以通过调用而不需要创建作为索引的循环来利用std::vector动态调整大小的能力。如果您事先知道要添加多少元素,为了避免不必要的调整大小,您可以调用where是您要添加的元素的数量。push_back()i.reserve(n)n

于 2012-10-18T21:57:19.583 回答
1

It's safe.

You could save boilerplate by moving all that filling into a constructor, if appropriate.

You might also be able to find a more efficient approach than levels of nested vectors.

So, it's safe but could still be improved.

于 2012-10-18T22:00:19.193 回答