fork download
  1. #include<algorithm>
  2. #include<iostream>
  3. #include<string>
  4. #include<vector>
  5. using namespace std;
  6.  
  7. struct X
  8. {
  9. string id, parent_id;
  10. int value, value_group = 0;
  11.  
  12. bool operator< (const X& x) const
  13. { return (value_group == x.value_group)? value < x.value : value_group < x.value_group; }
  14.  
  15. void print () const { cout << "{" << id << ", " << parent_id << ", " << value << ", " << value_group << "}\n"; }
  16. };
  17.  
  18. struct MyClass
  19. {
  20. vector<X> vx;
  21.  
  22. void Add (X&& x)
  23. {
  24. std::cout << "+++"; x.print();
  25. auto end = vx.end(), it = std::prev(end);
  26. bool isStandAlone = true;
  27. for(auto parent_id = x.parent_id;
  28. not parent_id.empty();
  29. parent_id = it->parent_id)
  30. for(auto itPrev = it - 1;
  31. parent_id != it->id or (isStandAlone = false);
  32. it = itPrev--)
  33. if(itPrev == vx.begin())
  34. {
  35. it->parent_id.clear();
  36. break;
  37. }
  38.  
  39. if(isStandAlone)
  40. x.parent_id.clear();
  41. else
  42. {
  43. auto begin = it;
  44. do { it->value_group = x.value; }
  45. while(++it != end and not it->parent_id.empty());
  46.  
  47. decltype(vx) temp(std::make_move_iterator(begin), std::make_move_iterator(it));
  48. vx.erase(begin, it);
  49. vx.insert(vx.end(), temp.begin(), temp.end());
  50. }
  51. x.value_group = x.value;
  52. vx.push_back(std::move(x));
  53. }
  54. };
  55.  
  56. void Print (const MyClass& obj)
  57. {
  58. std::cout << "\n===Print===\n";
  59. for(const auto& x : obj.vx)
  60. x.print();
  61. }
  62.  
  63. int main ()
  64. {
  65. MyClass obj;
  66. obj.Add({"dummy", "", 0});
  67. obj.Add({"c", "", 3});
  68. obj.Add({"dc", "c", 4});
  69. obj.Add({"b", "", 2});
  70. obj.Add({"a", "", 1});
  71. obj.Add({"ea", "a", 5});
  72. obj.Add({"fb", "b", 6});
  73. obj.Add({"ga", "a", 7});
  74. obj.Add({"ga1", "ga", 8});
  75. obj.Add({"ga2", "ga1", 9});
  76. obj.Add({"ea1", "ea", 10});
  77.  
  78. std::sort(obj.vx.begin(), obj.vx.end());
  79. Print(obj);
  80.  
  81. std::cout << "\n====Finished====\n";
  82. }
  83.  
Success #stdin #stdout 0s 15264KB
stdin
Standard input is empty
stdout
+++{dummy, , 0, 0}
+++{c, , 3, 0}
+++{dc, c, 4, 0}
+++{b, , 2, 0}
+++{a, , 1, 0}
+++{ea, a, 5, 0}
+++{fb, b, 6, 0}
+++{ga, a, 7, 0}
+++{ga1, ga, 8, 0}
+++{ga2, ga1, 9, 0}
+++{ea1, ea, 10, 0}

===Print===
{dummy, , 0, 0}
{c, , 3, 4}
{dc, c, 4, 4}
{b, , 2, 6}
{fb, b, 6, 6}
{a, , 1, 10}
{ea, a, 5, 10}
{ga, a, 7, 10}
{ga1, ga, 8, 10}
{ga2, ga1, 9, 10}
{ea1, ea, 10, 10}

====Finished====