Previous: Data Encapsulation, Up: Usage


2.3 Node Comparison

There are two situations in which nodes will be compared, either to other nodes or to key data. During node insertion, the inserted node's data is compared against other nodes' data to determine the proper ordering of the nodes. This operation uses the comparison routine passed to rbtree_new when the tree is created. The second situation is during searches of the tree, where node data is compared to some user specified data. Since the comparison routine passed to rbtree_new assumes the same form for both pieces of data passed to it for comparison, using it would require that the user create a dummy user node data structure (the same as the one associated with each node), and fill it with the key data, which in most instances will probably be one field. rbtree provides the possibility of using another comparison routine (passed to the search or destroy routines), which may compare data with two dissimilar forms. For example, assume that the user node data has the following structure, and keys on the ‘id’ value:

     typedef struct
     {
        int id;
        char *name;
     } UserNodeData;

The node comparison routine, used to compare nodes during insertion, would look like this:

     int node_node_compare(const void *dp1, const void *dp2)
     {
       return ((UserNodeData *)dp1)->id - ((UserNodeData *)dp2)->id;
     }

If you want to search the resultant tree, and not create a dummy UserNodeData structure, construct the search/destroy comparison routine as follows:

     int key_node_compare(const void *dp1, const void *dp2)
     {
       return *((int *) dp1) - ((UserNodeData *)dp2)->id;
     }

and pass the search/destroy routine a pointer to an int set equal to the id for which you're searching.

Several predefined comparison routines are available, but are of limited use. See rbtree_node_cmp_s. See rbtree_node_cmp_v.