#include<algorithm> #include<iostream> #include<string> #include<vector> using namespace std; struct X { string id, parent_id; int value, value_group = 0; bool operator< (const X& x) const { return (value_group == x.value_group)? value < x.value : value_group < x.value_group; } void print () const { cout << "{" << id << ", " << parent_id << ", " << value << ", " << value_group << "}\n"; } }; struct MyClass { vector<X> vx; void Add (X&& x) { std::cout << "+++"; x.print(); auto end = vx.end(), it = std::prev(end); bool isStandAlone = true; for(auto parent_id = x.parent_id; not parent_id.empty(); parent_id = it->parent_id) for(auto itPrev = it - 1; parent_id != it->id or (isStandAlone = false); it = itPrev--) if(itPrev == vx.begin()) { it->parent_id.clear(); break; } if(isStandAlone) x.parent_id.clear(); else { auto begin = it; do { it->value_group = x.value; } while(++it != end and not it->parent_id.empty()); decltype(vx) temp(std::make_move_iterator(begin), std::make_move_iterator(it)); vx.erase(begin, it); vx.insert(vx.end(), temp.begin(), temp.end()); } x.value_group = x.value; vx.push_back(std::move(x)); } }; void Print (const MyClass& obj) { std::cout << "\n===Print===\n"; for(const auto& x : obj.vx) x.print(); } int main () { MyClass obj; obj.Add({"dummy", "", 0}); obj.Add({"c", "", 3}); obj.Add({"dc", "c", 4}); obj.Add({"b", "", 2}); obj.Add({"a", "", 1}); obj.Add({"ea", "a", 5}); obj.Add({"fb", "b", 6}); obj.Add({"ga", "a", 7}); obj.Add({"ga1", "ga", 8}); obj.Add({"ga2", "ga1", 9}); obj.Add({"ea1", "ea", 10}); std::sort(obj.vx.begin(), obj.vx.end()); Print(obj); std::cout << "\n====Finished====\n"; }
Standard input is empty
+++{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====