doc_splaytree_algorithms.cpp 2.4 KB

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