doc_rbtree_algorithms.cpp 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2006-2013
  4. //
  5. // Distributed under the Boost Software License, Version 1.0.
  6. // (See accompanying file LICENSE_1_0.txt or copy at
  7. // http://www.boost.org/LICENSE_1_0.txt)
  8. //
  9. // See http://www.boost.org/libs/intrusive for documentation.
  10. //
  11. /////////////////////////////////////////////////////////////////////////////
  12. //[doc_rbtree_algorithms_code
  13. #include <boost/intrusive/rbtree_algorithms.hpp>
  14. #include <cassert>
  15. struct my_node
  16. {
  17. my_node(int i = 0)
  18. : int_(i)
  19. {}
  20. my_node *parent_, *left_, *right_;
  21. int color_;
  22. //other members
  23. int int_;
  24. };
  25. //Define our own rbtree_node_traits
  26. struct my_rbtree_node_traits
  27. {
  28. typedef my_node node;
  29. typedef my_node * node_ptr;
  30. typedef const my_node * const_node_ptr;
  31. typedef int color;
  32. static node_ptr get_parent(const_node_ptr n) { return n->parent_; }
  33. static void set_parent(node_ptr n, node_ptr parent){ n->parent_ = parent; }
  34. static node_ptr get_left(const_node_ptr n) { return n->left_; }
  35. static void set_left(node_ptr n, node_ptr left) { n->left_ = left; }
  36. static node_ptr get_right(const_node_ptr n) { return n->right_; }
  37. static void set_right(node_ptr n, node_ptr right) { n->right_ = right; }
  38. static color get_color(const_node_ptr n) { return n->color_; }
  39. static void set_color(node_ptr n, color c) { n->color_ = c; }
  40. static color black() { return color(0); }
  41. static color red() { return color(1); }
  42. };
  43. struct node_ptr_compare
  44. {
  45. bool operator()(const my_node *a, const my_node *b)
  46. { return a->int_ < b->int_; }
  47. };
  48. int main()
  49. {
  50. typedef boost::intrusive::rbtree_algorithms<my_rbtree_node_traits> algo;
  51. my_node header, two(2), three(3);
  52. //Create an empty rbtree container:
  53. //"header" will be the header node of the tree
  54. algo::init_header(&header);
  55. //Now insert node "two" in the tree using the sorting functor
  56. algo::insert_equal_upper_bound(&header, &two, node_ptr_compare());
  57. //Now insert node "three" in the tree using the sorting functor
  58. algo::insert_equal_lower_bound(&header, &three, node_ptr_compare());
  59. //Now take the first node (the left node of the header)
  60. my_node *n = header.left_;
  61. assert(n == &two);
  62. //Now go to the next node
  63. n = algo::next_node(n);
  64. assert(n == &three);
  65. //Erase a node just using a pointer to it
  66. algo::unlink(&two);
  67. //Erase a node using also the header (faster)
  68. algo::erase(&header, &three);
  69. return 0;
  70. }
  71. //]