I had a problem with iterators. What should I do if I have an iterator for the tree, and there is a need to implement the erase function in order to start deleting tree nodes от first до last ?

The problem is that I have in the iterator a pointer to a specific tree element, and the iterator functions are actively working with it.

But if you delete the node to which the iterator is pointing, the link is no longer active, the whole for goes to the tail, and the ++ increment operator cannot move to the next node.

Could you tell me how to solve this problem?

PS If necessary, attach examples of the iterator code and delete the tree element.

  • In the standard library, situations where deleting an item makes an iterator invalid are very common ... Act differently, without trying to delete items in an old way through an iterator. - Harry

2 answers 2

Return from erase iterator to the element following the deleted one, so you will always be able to continue traversing the tree.

  • I'm sorry, I checked your version. It does not fit, my erase training manual should be similar to erase in map, and therefore return the void. - Demolver
  • @Demolver, this is what he used to return void , now returns an iterator - ixSci

Try writing a recursive function. Something like this:

 void deleteItems(Tree& tree, Item* itemToDelete, const Item* lastItem) { if (itemToDelete != lastItem) { deleteItems(tree, itemToDelete->nextItem(), lastItem); } tree.deleteItem(itemToDelete); }