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;
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).
Thanks!
If your
motherpointers point directly to elements of thepiecesvector you will get in all kinds of trouble.Deleting an element from
pieceswill 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.
Not storing pointers into
piecesasmotherbut instead the indexes of the elements would make it a bit more robust, so that at least inserting new elements could not break the existingmothers. But deleting frompieceswould still shift elements to new indexes.Using a
std::listforpiecesand storing iterators into that asmothermight be a solution. Iterators ofstd::listare not invalidated if other elements are of that list are removed/added. If different elements can have the samemotheryou still have a problem finding out when to remove themotherelements, than maybe usingboost::shared_ptrwould be simpler.