STL 向量和指向向量元素的指针
有两种 STL 向量,第一个包含对象,第二个包含指向对象的指针。
v_objects = [obj1, obj2, obj3, obj4]
v_ptr = [ptr_to_obj1, ptr_to_obj2, ptr_to_obj3, ptr_to_obj4]
向量 v_ptr 用于对 v_objects 中的元素进行排序。假设向 v_objects 添加了一些内容,如下所示:
v_objects = [obj1, obj2, obj3, obj4, obj5]
假设 v_objects 在插入后被重新分配到其他位置,并且 v_ptr 中的指针无效。现在我想使用 v_ptr 中的指针对对象进行排序,但它们无效。是否可以以某种方式创建一些聪明的指针,这些指针指向与重新分配之前相同的对象(使用 stl::vector)?
There are two STL vectors, one with objects and second with pointers to objects.
v_objects = [obj1, obj2, obj3, obj4]
v_ptr = [ptr_to_obj1, ptr_to_obj2, ptr_to_obj3, ptr_to_obj4]
Vector v_ptr is used to sort elements in v_objects. Let's say that something is added to v_objects so it looks like:
v_objects = [obj1, obj2, obj3, obj4, obj5]
Let's say that v_objects are after insertion reallocated somewhere else and pointers in v_ptr are invalid. Now I want to sort objects using their pointers in v_ptr, but they are invalid. Is it somehow possible to create some clever pointers which point to the same object as they were before reallocation (using stl::vector)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不这么认为。您可以通过使用带有 < 的单个向量来省去麻烦。 code>shared_ptr 到你的对象,或者只使用
ptr_vector
。I don't think so. You could probably save yourself the trouble by just using a single vector with
shared_ptr
s to your objects, or just use aptr_vector
.有几种方法可以解决这个问题:
v_objects
来存储指向对象的指针(这将使内存管理复杂化,但使用智能指针可能会有所帮助)。v_ptr
以将索引存储到v_objects
而不是指针。我个人的偏好是后者。
There are several ways to tackle this:
v_objects
to store pointers to objects (this will complicate memory management, but using smart pointers might help).v_ptr
to store indices intov_objects
instead of pointers.My personal preference would be the latter.
我不完全理解你想要做什么,但你可以将索引存储到容器中,而不是指针。用于排序的比较器函子将存储对向量的引用并取消引用元素以获得值。
只要原始向量中元素的顺序不改变(即仅在末尾插入),索引向量仍然有效。如何处理新添加的元素,或者是否对原始向量执行任何其他更改是另一回事:
I don't fully understand what you want to do, but you could store indices into the container, rather than pointers. The comparator functor for the sorting would store a reference to the vector and dereference the elements to obtain the values.
As long as the order of the elements in the original vector does not change (i.e. only insertions at the end) the vector of indices would still be valid. What to do with the newly added elements, or if any other change is performed on the original vector is a different story: