简体   繁体   中英

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:

#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? There would be any memory related issue? Is there any better way of initializing objects dynamically (ie not in constructor)? 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.

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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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