doc_splay_algorithms.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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_splaytree_algorithms_code
  13. #include <boost/intrusive/splaytree_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 splaytree_node_traits
  26. struct my_splaytree_node_traits
  27. {
  28. typedef my_node node;
  29. typedef my_node * node_ptr;
  30. typedef const my_node * const_node_ptr;
  31. static node_ptr get_parent(const_node_ptr n) { return n->parent_; }
  32. static void set_parent(node_ptr n, node_ptr parent){ n->parent_ = parent; }
  33. static node_ptr get_left(const_node_ptr n) { return n->left_; }
  34. static void set_left(node_ptr n, node_ptr left) { n->left_ = left; }
  35. static node_ptr get_right(const_node_ptr n) { return n->right_; }
  36. static void set_right(node_ptr n, node_ptr right) { n->right_ = right; }
  37. };
  38. struct node_ptr_compare
  39. {
  40. bool operator()(const my_node *a, const my_node *b)
  41. { return a->int_ < b->int_; }
  42. };
  43. int main()
  44. {
  45. typedef boost::intrusive::splaytree_algorithms<my_splaytree_node_traits> algo;
  46. my_node header, two(2), three(3);
  47. //Create an empty splaytree container:
  48. //"header" will be the header node of the tree
  49. algo::init_header(&header);
  50. //Now insert node "two" in the tree using the sorting functor
  51. algo::insert_equal_upper_bound(&header, &two, node_ptr_compare());
  52. //Now insert node "three" in the tree using the sorting functor
  53. algo::insert_equal_lower_bound(&header, &three, node_ptr_compare());
  54. //Now take the first node (the left node of the header)
  55. my_node *n = header.left_;
  56. assert(n == &two);
  57. //Now go to the next node
  58. n = algo::next_node(n);
  59. assert(n == &three);
  60. //Erase a node just using a pointer to it
  61. algo::unlink(&two);
  62. //Erase a node using also the header (faster)
  63. algo::erase(&header, &three);
  64. return 0;
  65. }
  66. //]