I have a property tree where all the data is stored in its leaf nodes. The Tree, however, has a complex structure. What I want to do now is:
- get all (and only the) leaf nodes of the tree, for they contain the data and
- recall the path leading to the respective leaf node
Eventually, I want to receive a key/value pair of all (and only the) leaf nodes where the key contains the complete path to the node and the value contains the node's value.
My questions are:
- Is there a more convenient way than to recursively iterate through the whole tree, store the respective path and read out the values of the nodes that don't have children (i.e. a "get_leaves()" function)?
- If I have some pointer to a subtree (ptree variable, iterator, whatever..) of a given tree, is there a method to easily determine the relative path of that subtree inside the tree?
I'd just write some helper functions. They're really not that difficult. Here's a completely generic tree visitation function that optionally takes a predicate:
You can use it with a predicate like
And here's a simple demo:
Live On Coliru
Prints:
UPDATE
Just noted the second half of the question. here's how to do it using the same visitor:
And a demo Live On Coliru