Frage

I'm trying to implement an N-ary Tree in c++ using the glib, but as I'm not a c++ expert, I'm having some problems finding out how to use it right. Does anybody have a simple example written in C++ to help me understand how to use the basic functions? I'm having special problems with g_node_traverse, I just can't get the GNodeTraverseFunc right.

You can find the description of the N-ary Tree here: http://developer.gnome.org/glib/stable/glib-N-ary-Trees.html

I found some examples in c, but I couldn't manage to translate them correctly into c++ here:

http://www.ibm.com/developerworks/linux/tutorials/l-glib/section7.html

Tried with the last piece of code for n-ary trees.

I appreciate your help.

War es hilfreich?

Lösung


Well, I have managed to run some code. The problem was basically the casts that were needed because Gnome uses gpointers and my data is to be stored in a struct. So my code is:

    gboolean iter(GNode* n, gpointer data) {
     node s=*(node *)(n->data);
     int ID=g_node_depth(n);

     if (G_NODE_IS_ROOT(n)==true)
     {
         std::cout<<"Node "<<ID<<" is a Root"<<std::endl;
     }
     else if (G_NODE_IS_LEAF(n)==true)
     {
         std::cout<<"Node "<<ID<<" is a Leaf"<<std::endl;
     }

     std::cout<<"Speed of Node "<<ID<<" is: "<<s.v<<std::endl;
     return FALSE;
    }

    int main(){

        node prueba,prueba1;
        prueba.phi=0; 
        prueba.v=1;   
        prueba.x=50;  
        prueba.y=100; //Position in y

        prueba1.phi=90;
        prueba1.v=6;
        prueba1.x=30;
        prueba1.y=90;

        GNode * root = g_node_new((gpointer) &prueba);
        g_node_append(root, g_node_new((gpointer) &prueba1));

        g_node_traverse(root, G_PRE_ORDER, G_TRAVERSE_ALL, -1, iter, NULL);

     return 0;

    }

Where my struct is:

    struct state {
        double x;    //Position in x of a car
        double y;    //Position in y "
        double phi; //Yaw angle of a car
        double v;   //Speed of a car
    };


    struct node {
        double x;
        double y;
        double phi;
        double v;
        std::vector <state > trajectory;
    };

The idea is to have the whole previous "trajectory" stored at each node so if I choose a random node/leaf I don't have to reconstruct the trajectory but just take it.

This code works now. It might be improved and I'm open to any comment.

I hope it's useful for someone.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top