2

I want to do a pre-order traversal of an n-array tree. My tree node struct contains a vector pointer member. So, how can I iteratively call the members.

I want to do something like:

for(i in node->children){
    cout<<i;
}

The Node class is defined as follows:

class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
Botje
  • 26,269
  • 3
  • 31
  • 41
  • 4
    Well, your current code allows `for (Node* c : node->children) { cout << *c; }` If that is not good enough you will have to implement `begin` and `end` yourself, returning an iterator that yields *references* to Nodes instead of pointers. – Botje May 21 '19 at 07:34
  • 1
    @Botje why does he need to implement begin and end? `node->children` is a vector. – Jabberwocky May 21 '19 at 07:55
  • What if OP *really* wanted to write `for (Node& c : node->children) { ... }` or even `for (Node& c : node) { ... }` ? A vector of pointers is often not nice to work with. – Botje May 21 '19 at 07:57
  • @Botje If the OP wants your first possibility, then it would be necessary to change `Node::children` so it has type `vector` rather than `vector`. If the OP wants your second option, it would be necessary to implement an an appropriate iterator type and `begin()` and `end()` member functions for class `Node`. – Peter May 21 '19 at 08:23

1 Answers1

4
for (Node *child: node->children) {
    // do something with child
}
Brennan Vincent
  • 10,736
  • 9
  • 32
  • 54