Reputation: 11739
What would be the best algorithm for the undermentioned problem.
Implement method PrintFamilyTree() that prints out the Name and Generation of the tree
Output should resemble
Name: Jan Generation:0
Name: Mike Generation:1
Name: Greg Generation:2
Name: Carol: Generation: 2
Name: Peter Generation: 3
Name: Marcia Generation: 3
Name: Bobby Generation: 1
class Human : public std::vector<Human *>
{
public:
Human(const std::string &name) : m_Name(name) {};
virtual void PrintFamilyTree(const short &generation = 0) const;
protected:
std::string m_Name;
};
class Male: public Human
{
public:
Male(const std::string &name) : Human(name) {};
};
class Female: public Human
{
public:
Female(const std::string &name) : Human(name) {};
};
void main()
{
Male m1("Mike"), m2("Greg"), m3("Peter"), m4("Bobby");
Female f1("Carol"), f2("Marcia"), f3("Jan");
m1.push_back(&m2);
f1.push_back(&m3);
f1.push_back(&f2);
m1.push_back(&f1);
f3.push_back(&m1);
f3.push_back(&m4);
f3.PrintFamilyTree();
}
Upvotes: 0
Views: 171
Reputation: 48330
For the algorithm I think a Topological sort will fit, but you need a graph not a vector
Upvotes: 1
Reputation: 7446
Upvotes: 0
Reputation: 111130
class Human : public std::vector<Human *>
Not a good idea -- STL containers are typically not designed to be derived from. Think of containment rather than inheritance.
void main()
main
returns an int
. Always.
This looks like a straight-forward problem. Think of a tree-like structure. You may want to change the container you are using (i.e. vector
) to something more suitable.
Be warned, your question smells a lot like homework, so there'd be few responses!
Upvotes: 5