Remove repeated nodes in a Hierarchical tree

I have a Node class that contain other nodes childs. I want to compare all childs node with all fathers node and remove the duplicated fathers nodes. I propose the next code which generates a segmentation fault when father is NOT in the last position of the fathers nodes vector or when the position of the compaired child is NOT in the last position of childs vectors .
How I can avoid segmentation fault?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Node : public std::enable_shared_from_this<Node>
{
    public:
        Node(int i);
        typedef std::vector<std::shared_ptr<Node>> vector;
        std::vector<std::shared_ptr<Node>> childs;
        int id;
};

Node::Node (int i): id{i}{

}

int main(int argc, char* argv[])
{
    Node::vector trees;
    trees.push_back(std::make_shared<Node>(11));
    trees.push_back(std::make_shared<Node>(10));
    trees.push_back(std::make_shared<Node>(7));
    trees.push_back(std::make_shared<Node>(2));     // Crashed when 2 is not in the last position.
    trees.push_back(std::make_shared<Node>(9));     // If 2 is set in this position it does not crash.

    int i = 0;
    for (auto && tree : trees)
    {
        tree->childs.push_back(std::make_shared<Node>(i));
        i++;
    }

    for (auto && tree : trees)
    {
        for (auto && child : tree->childs)
        {
            trees.erase(std::remove_if(trees.begin(), trees.end(), [&](std::shared_ptr<Node> ptr)
            {
                            return (ptr->id == child->id);
                        }), trees.end());
        }
    }

    return 0;
}
Last edited on
Iterator validity.

You have essentially three nested loops on lines 30, 32, and 34.
You might erase multiple vector elements (and entire "childs" vectors).
Erase can invalidate iterators. Your loops clearly do not anticipate that.
Topic archived. No new replies allowed.