简体   繁体   English

在结构中创建某个结构的数组。

[英]Making an array of a certain struct within the struct.

I have a structure called scene. 我有一个叫做场景的结构。 Within the structure called scene, I need to make an array of other scene objects. 在名为scene的结构中,我需要创建一个其他场景对象的数组。 Is this possible? 这可能吗?

No, because before scene is completely defined, the compiler doesn't know how big it is, and doesn't know what size to make the array. 不,因为在scene完全定义之前,编译器不知道它有多大,并且不知道制作阵列的大小。

However, you can have an array of pointers to scene , because pointers (not counting pointers to members and other oddities - thanks Nawaz) are all the same size: 但是,你可以有一个指向 scene指针数组,因为指针(不计算指向成员的指针和其他奇怪的东西 - 感谢Nawaz)都是相同的大小:

class scene {
    scene* array[20];
};

Alternatively, you can store a pointer that will point to a dynamic array allocated with new[] and deallocated with delete[] : 或者,您可以存储指向使用new[]分配的动态数组并使用delete[]解除分配的指针:

class scene {
    scene() : array(new scene[20]) { }
    ~scene() { delete[] array; }

    scene* array;
};

or even more alternatively, store a vector<scene> , a vector of scene s: 或者更确切地说,存储一个vector<scene> ,一个scene vector

class scene {
    vector<scene> array;
};

and with vector , you get a resizable array with no manual memory management. 并使用vector ,您将获得一个可调整大小的数组,没有手动内存管理。

Yes. 是。 You can do that. 你可以做到这一点。 But you've to declare the member as pointer as: 但是你要将成员声明为指针

struct scene
{
     //other members

     scene *children; //this is what you need.
                      //you cannot make it like : scene children[100];
};

Then create the dynamic array as: 然后创建动态数组:

scene parent;
parent.chidren = new scene[100]; //100 children!

Just remember that you've to allocate and deallocate the memory yourself. 请记住,您必须自己分配和释放内存。

Alternatively, you can use std::vector<scene*> , or boost::ptr_vector<scene> . 或者,您可以使用std::vector<scene*>boost::ptr_vector<scene>

Sure it is possible. 当然有可能。

Pseudocode: 伪代码:

struct Scene {
   int id;
   Scene* scenes;
};

PS. PS。 you could easily test this - do not be so lazy. 你可以很容易地测试一下 - 不要太懒。 ;) ;)

You can do it if you use std::vector . 如果你使用std::vector你可以这样做。 This is from some code I wrote yesterday: 这是我昨天写的一些代码:

#include <vector>
struct ChangeList // Tree of changes in a tree of values
  {
  int index ;
  std::vector<ChangeList> Changes ;
  } ;

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

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