Avatar ·

How to detect and prevent cycles in a family tree in C++?

Hello everyone! I'm writing a program for building a family tree in C++. I've encountered a serious problem: when adding family relationships, the user can accidentally create a cycle. For example, specifying that a grandfather is the grandson of his own grandson. The program hangs or crashes with a segmentation fault when trying to traverse the tree. My data structure looks like this: ```cpp struct Person { string name; vector parents; vector children; }; ``` I add a "parent-child" relationship approximately like this: ```cpp void addParentChild(Person* parent, Person* child) { parent->children.push_back(child); child->parents.push_back(parent); } ``` The user enters data in arbitrary order, and I cannot guarantee that a cycle will not occur. For example