I have objects in a tree data structure and need a function to explore an object's parents/grandparents. I've written the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void findEntsAtLevel(EntityID id, PairIdUnitsVec& pairvec) //pairvec is passed by reference as it captures all parents/grandparents etc
{
PairIdUnitsVec prts_v = getParents(id); //gets a vector of an objects immediate parents
if (prts_v.size() <= 0) //no parents for this ent so go back (this ent will have been captured in the calling function)
{
return;
}
for (PairIdUnits prt : prts_v) //iterate over each parent and call function recursively
{
pairvec.push_back(prt);
findEntsAtLevel(prt.related_ent_id, pairvec);
}
}
This seems to work but I'd be grateful for any thoughts e.g. is passing the vector by reference good practice or should I try to be returning values (if that is possible here).
What your describing isn't a tree, or it is a tree but you've reversed the terms parents/children. Can you describe your data structure a little better?
I think for what you're describing, I would make a function in my Node class like this (pseudocode)
1 2 3 4 5 6
Node::enumerateParents(depth, function)
{
if depth is 0:
do function()
elsefor each parent of *this, do enumerateParents(depth-1, function)
}