简体   繁体   English

C ++ :: vector中的vector作为另一个vector的数据类型

[英]C++::vector of vector in `struct` as data type of another vector

I am working on a physics engine related project. 我正在从事与物理引擎相关的项目。 In the C++ code below: 在下面的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;
}

is the way I have allocated memory for objects of world safe? world objects分配内存的方式安全吗? There would be any memory related issue? 会有与记忆有关的问题吗? Is there any better way of initializing objects dynamically (ie not in constructor)? 有没有更好的方法来动态初始化objects (即不在构造函数中)? If so, how? 如果是这样,怎么办? thanks. 谢谢。

I'd imagine that using RAII and having the constructor and destructor of object to take care of the memory would be a better way of doing this. 我以为使用RAII并让object的构造函数和析构函数处理内存将是一种更好的方法。

Adding in a new object into world you can make use of std::vector ability to resize dynamically by just calling push_back() instead of needing to create the loop that has i as the index. 在世界中添加一个新object您可以利用std::vector功能来动态调整大小,只需调用push_back()而无需创建以i为索引的循环。 To avoid unnecessary resizes if you know how many elements you are adding in advance you can call .reserve(n) where n is the number of elements you are adding. 若要避免不必要的调整大小,如果您事先知道要添加多少个元素,可以调用.reserve(n) ,其中n是要添加的元素数。

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. 因此,它是安全的,但仍可以改进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM