3

Personalized itinerary on a c ++ tree

 3 years ago
source link: https://www.codesd.com/item/personalized-itinerary-on-a-c-tree.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Personalized itinerary on a c ++ tree

advertisements

I am implementing a tree structure in c++ with a node class like this:

class Node {
protected:
    // relations
    Node *_parent;
    std::vector<Node*> _children;

public:
    // some example method
    void someMethod(Node *node) {

        // do something with *node

        for (int i = 0; i < node->_children; i++) {
            _children[i]->myFunction;
        }
    }
}

Now, to work on the nodes in my tree I am implementing recursive functions like someMethod in my example.

It works, but I end up writing the same recursion code over and over again for every new function that works on my tree.

Is there a generic way to iterate a tree structure like I would on a plain array? Some method that returns the next object, until I'm done with the whole branch.

EDIT:

Thanks to everybody who has commented so far, with your help I could narrow down the problem. From my understanding (I'm new to c++), I need an iterator class that encapsulates the code for traversing my tree.

Accessing all tree members should be as simple as that:

for (Node<Node*>::iterator it = _node.begin(); it != _node.end(); ++it) {
    Node *node = *it;
    // do something with *node
}

Now the question is:

How do I implement such an iterator?


Pass a function pointer to the recursive function that returns the node that you are seeking.

This is the power of function pointers and function pointer arrays in C/C++.

Tags tree

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK