如何保存类的实例列表?
我正在用 C++ 编写光线跟踪器,需要能够检查场景中每个对象的交集(稍后会进行优化),为此,我需要保留类实例的运行列表。创建新实例时更新的指针列表将不起作用,因为据我所知,在初始化后无法增加数组的大小。如果有的话,我真的很想要一个内置的(C++)解决方案。
I'm writing a raytracer in C++ and need to be able to check intersections with every object in a scene (optimizations will come later), and to do this, I need to keep a running list of class instances. A list of pointers, updated when a new instance is created, won't work because as far as I know there is no way to increase the size of the array after it is initialized. I'd really like a built-in (to C++) solution if there is one.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用任意数量的 STL 容器。
STL 容器参考
There are any number of STL Containers you could use.
STL Container Reference
创建一个指向场景中对象的指针的
向量
(或集
)作为静态类成员,并让所有的构造函数将this
插入到集合,dtor
从集合中删除this
:Create a
vector
(orset
) of pointers to the objects in your scene as a static class member, and have all your ctors insertthis
into the collection, and thedtor
deletethis
from the collection:标准方法是空间图。最常见的是使用八叉树,因为它们可以表达 3 维空间中的位置。简而言之,空间树看起来像这样:
每个节点都有一个(隐式或显式)位置和大小。当一个新对象被添加到世界场景中时,树会遍历子对象(它们占据由 xy、yz 和 zx 平面分割的八分圆:上面 4 个,下面 4 个;左边 4 个,右边 4 个;后面 4 个) ,前面的4)并且该对象仅添加到可以完全包含它的最小节点。 (显然,您需要能够计算对象的尺寸以及它们是否可以完全包含在给定区域内。)
这样做的好处是相当快(实际上只有被检查的树的部分)相关),无论是在填充它还是在搜索它。您可以在 Wikipedia、GameDev.net 和其他地方阅读有关它的多篇文章。
The standard approach is a spatial graph. Most commonly, octrees are used, since they can express location in 3-dimensional space. Trivially, the spatial tree would look something like this:
Each node has an (implicit or explicit) position and size. When a new object is added to the world scene, the tree is walked through the children (which occupy the octants that are split by the x-y, y-z, and z-x planes: 4 above, 4 below; 4 left, 4 right; 4 behind, 4 in front) and the object is added only to the smallest node that can fully contain it. (Obviously, you'll need to be able to calculate the dimensions of your object and whether they can be fully contained within a given region.)
This has the benefit of being fairly fast (only the portions of the tree that are examined are actually relevant), both in populating it and in searching it. There are several articles on it that you can read at Wikipedia, GameDev.net, and elsewhere.
std::vector
应该没问题(并且它是 C++ 标准的一部分)。A
std::vector
should be fine (and it is part of the C++ standard).