Ok, so I'm really struggeling to find a good solution to this (presumably) simple problem:
Given a class of objects, where each object can have one parent, and each parent can have multiple childs:
class Object
{
public:
bool IsBaseOf(const Object& child) const noexcept;
private:
Object* m_pBase;
};
How would I sort an array of X “objects” in an order, where the base-classes always come before their respective childs? I tried simply using the IsBaseOf to establish a weak-order by essentially saying “A < B if A is a base of B", but I'm not getting the correct results (I assume because the default sort-algorithm simply doesn't work with the type of mixed-sorting where only particular elements are in a certain order:
std::vector<Object*> vObjects;
// doesn't really work some of the time
std::sort(vObjects.begin(), vObjects.end(), [](const Object* pA, const ObjectA* pB)
{
return pA->IsBaseOf(*pB);
});
Any ideas on a (somewhat efficient) and elegant way of achieving this? I know I could do crazy things like getting all root-objects, then traversing their children and putting all that are in that vector as well simply in the order of traversal, but I'm interested in whether there is somehing less complicated.