c++quadtree

Method to get the children of a node in quadtree


I'm trying to recursively get all the children of a node using the method below. getchildren(), addChildren() and the constructor for the Node work fine but when I try to get the children using the method below, the vector kids seems to be empty and I don't understand why given that inside the method when I print n.getX() and n.getY() , it prints the values, so kids shouldn't be empty. This is the code:

void Quad::getChildren(Node n, vector<Node> kids)
{
    if(n.getchildren().empty())
    {
        cout<<"NOOO";
        return;
    }
    else
    {
        for(Node child: n.getchildren())
        {
            kids.push_back(child);
            getChildren(child, kids);
        }
    
        for(Node n: kids)
            cout<<n.getX()<<' '<<n.gety()<<endl;
    }
}
    

used like:

vector<Node> kids;
Node n1= Node(0,0,img.cols,img.rows);
Node n2= Node(12,19,34,33);
n1.addChildren(n2);
getChildren(n1,kids);
    
if(kids.empty())
    cout<<"sedfeesdsed";

and the OUTPUT:

NOOONOOO12 19
sedfeesdsed

At the moment I can only debug using cout<< unfortunately.


Solution

  • kids should be a reference. You are passing the vector by copy, instead of a reference. vector kids is a local for the method, pushing anything into it is not pushed into the vector kids from the caller.

    void Quad::getChildren(Node n, vector<Node>& kids)
    //                                         ^ reference