erikerlandson / st_tree

A fast and flexible c++ template class for tree data structures
https://github.com/erikerlandson/st_tree/wiki
Apache License 2.0
96 stars 20 forks source link

Not possible to navigate up all parents to the tree root #36

Open macdew opened 2 years ago

macdew commented 2 years ago

In my scenario, I have an st_tree and an iterator to an arbitrary node in the tree. I then try to build the path for that node by visiting every parent node back to the tree root. However, this kind of loop doesn't work:

auto& parent_node = iterator_to_tree_node->parent();
while (!parent_node.is_root())
{
  // do something with parent_node.data();
  parent_node = parent_node.parent();
}

In the last line, parent_node = parent_node.parent() triggers the operator=() for node_type, and thus starts a graft.

I'm not sure that this operator=() is necessary to have as a node assignment? Perhaps a method should do this instead?

Alternatively, perhaps it would be an idea to add a parent-visitor iterator that could navigate up the tree?

In the end I solved this by using a recursive lambda to visit each parent, thus avoiding the assignment, but it feels a bit overkill to solve this problem that way.

erikerlandson commented 2 years ago

@macdew thanks for pointing this out, that is a bit unintuitive. I'm not immediately sure what to do in terms of backward compatibility - I'd hate to break people's code if they are making use of the current semantic.

Maybe making parent_node a pointer to a node, and using parent_node = &(parent_node.parent()) ? Not really a modern c++ pattern, though.

A new kind of iterator is definitely plausible.