C ++ - 删除指针引用的向量元素 [英] C++ - Deleting a vector element that is referenced by a pointer

查看:269
本文介绍了C ++ - 删除指针引用的向量元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我不知道是否可能,但事情会是:

Well, I don't know if it is possible, but the thing would be:

struct stPiece
{
  /* some stuff */
  stPiece *mother; // pointer to the piece that created this one
};

vector<stPiece> pieces;

可以删除由mother引用的作品,参考?如何?

Is it possible to erase the piece referenced by 'mother' from pieces, having just that pointer as a reference? How?

会不会与其他参考? (即,如果它不是向量中的最后一个元素,通过将下一个元素移动到其他存储器位置,而其他'*个母亲保持不变)。当然,我假设所有的子件将被删除(所以我不需要更新任何指向同一个母亲的指针)。

Would it mess with the other references? (i.e. if it is not the last element in the vector, by shifting the next elements to other memory positions, while the other '*mothers' remain constant). Of course, I assuming that all the child pieces will be deleted (so I won't need to update any pointer that goes to the same mother).

谢谢! / p>

Thanks!

推荐答案

如果您的 mother 指针直接指向<$ c

If your mother pointers point directly to elements of the pieces vector you will get in all kinds of trouble.

件中删除一个元素将在较高索引处移动元素的所有位置。即使插入元素也可以使所有指针无效,因为向量可能需要重新分配它的内部数组,这可能将所有元素转移到内存中的新位置。

Deleting an element from pieces will shift all the positions of the elements at higher indexes. Even inserting elements can make all the pointers invalid, since the vector might need to reallocate it's internal array which might transfer all the elements to new positions in memory.

主要问题:你不能直接删除你有指针的元素,你首先需要通过向量搜索来找到它,或者计算它在向量中的索引。

To answer your main question: You can't delete the element you have the pointer to directly, you would first need search through the vector to find it, or calculate it's index in the vector.

不将指针存储到中作为 mother ,而是元素的索引会使它更健壮,所以至少插入新元素不能打破现有的

Not storing pointers into pieces as mother but instead the indexes of the elements would make it a bit more robust, so that at least inserting new elements could not break the existing mothers. But deleting from pieces would still shift elements to new indexes.

使用

Using a std::list for pieces and storing iterators into that as mother might be a solution. Iterators of std::list are not invalidated if other elements are of that list are removed/added. If different elements can have the same mother you still have a problem finding out when to remove the mother elements, than maybe using boost::shared_ptr would be simpler.

这篇关于C ++ - 删除指针引用的向量元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆