fork(3) download
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <memory>
  5. using namespace std;
  6.  
  7. // char* replaced with strings
  8. // Node*[] repaced with vector
  9. // Node* replaced with shared_ptr
  10.  
  11. struct Skill {
  12. string name, desc;
  13. int level;
  14. Skill() = default;
  15. Skill(string& name, string& desc, int level) : name(name), desc(desc), level(level) {}
  16. };
  17. struct Node {
  18. weak_ptr<Node> parent;
  19. Skill sk;
  20. vector<shared_ptr<Node>>children;
  21. Node() = default;
  22. Node(Skill s) : sk(s) {}
  23. void show(int n) {
  24. cout << string(n * 2, ' ') << sk.name << endl;
  25. for (auto &x : children) // easy way to traverse a vector, intead of for (i=0; i<...; i++)
  26. x->show(n + 1);
  27. }
  28. };
  29. class Tree {
  30. public:
  31. shared_ptr<Node>root;
  32. void show() { root->show(0); }
  33. void AddSkill(string name, string desc, int level);
  34. void AddSkill(string name, string desc, int level, string parentname);
  35. protected:
  36. void AddSkill(shared_ptr<Node>n, Skill&s, string &parentname); // helper for recursive search
  37. };
  38.  
  39. void Tree::AddSkill(string name, string desc, int level)
  40. {
  41. Skill s(name, desc, level);
  42. shared_ptr<Node> newNode = make_shared<Node>(s); // like new Node(s) but for shared pointers
  43. if (root == NULL)
  44. root = newNode;
  45. else
  46. {
  47. root->parent = newNode;
  48. newNode->children.push_back(root);
  49. root = newNode;
  50. }
  51. }
  52.  
  53. void Tree::AddSkill(shared_ptr<Node>node, Skill& s, string& parentName)
  54. {
  55. if (node->sk.name == parentName) { // if found, add the new node as childen
  56. shared_ptr<Node> child = make_shared<Node>(s); // like new Node(s) but for shared pointers
  57. child->parent = node;
  58. node->children.push_back(child);
  59. }
  60. else {
  61. for (auto &x : node->children) // for all the children
  62. AddSkill(x, s, parentName); // search recursively
  63. }
  64. }
  65.  
  66. void Tree::AddSkill(string name, string desc, int level, string parentName)
  67. {
  68. if (root == NULL)
  69. {
  70. cout << "Error: no nodes in tree.\n";
  71. return;
  72. }
  73. Skill s(name, desc, level);
  74. AddSkill(root, s, parentName);
  75. }
  76.  
  77. int main()
  78. {
  79. Tree t;
  80. t.AddSkill("main", "", 0);
  81. t.AddSkill("IT", "", 0, "main");
  82. t.AddSkill("Management", "", 0, "main");
  83. t.AddSkill("C++", "", 100, "IT");
  84. t.AddSkill("Java", "", 100, "IT");
  85. t.AddSkill("SQL", "", 100, "IT");
  86. t.show();
  87. cin.get();
  88. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
main
  IT
    C++
    Java
    SQL
  Management