README 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #include <grass/rbtree.h>
  2. and link to BTREE2LIB
  3. to make use of this binary balanced (Red-Black) search tree
  4. NOTE: duplicates are not supported
  5. USAGE
  6. =====
  7. see also grass/rbtree.h for instructions on how to use it
  8. /* custom compare function */
  9. extern int my_compare_fn(const void *, const void *);
  10. int my_compare_fn(const void *a, const void *b)
  11. {
  12. if ((mydatastruct *) a < (mydatastruct *) b)
  13. return -1;
  14. else if ((mydatastruct *) a > (mydatastruct *) b)
  15. return 1;
  16. else if ((mydatastruct *) a == (mydatastruct *) b)
  17. return 0;
  18. }
  19. /* create and initialize tree: */
  20. struct RB_TREE *mytree = rbtree_create(my_compare_fn, item_size);
  21. /* insert items to tree: */
  22. struct mydatastruct data = <some data>;
  23. if (rbtree_insert(mytree, &data) == 0)
  24. G_warning("could not insert data");
  25. /* find item in tree: */
  26. struct mydatastruct data = <some data>;
  27. if (rbtree_find(mytree, &data) == 0)
  28. G_message("data not found");
  29. /* delete item from tree: */
  30. struct mydatastruct data = <some data>;
  31. if (rbtree_remove(mytree, &data) == 0)
  32. G_warning("could not find data in tree");
  33. /* traverse tree (get all items in tree in ascending order): */
  34. struct RB_TRAV trav;
  35. rbtree_init_trav(&trav, tree);
  36. while ((data = rbtree_traverse(&trav)) != NULL) {
  37. if (my_compare_fn(data, threshold_data) == 0) break;
  38. /* do something with data */
  39. }
  40. /* get a selection of items: all data > data1 and < data2
  41. * start in tree where data is last smaller or first larger compared to data1 */
  42. struct RB_TRAV trav;
  43. rbtree_init_trav(&trav, tree);
  44. data = rbtree_traverse_start(&trav, &data1);
  45. /* do something with data */
  46. while ((data = rbtree_traverse(&trav)) != NULL) {
  47. if (data > data2) break;
  48. /* do something with data */
  49. }
  50. /* destroy tree: */
  51. rbtree_destroy(mytree);
  52. /* debug the whole tree with */
  53. rbtree_debug(mytree, mytree->root);