doc_treap_algorithms.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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_treap_algorithms_code
  13. #include <boost/intrusive/treap_algorithms.hpp>
  14. #include <cassert>
  15. struct my_node
  16. {
  17. my_node(int i = 0, unsigned int priority = 0)
  18. : prio_(priority), int_(i)
  19. {}
  20. my_node *parent_, *left_, *right_;
  21. int prio_;
  22. //other members
  23. int int_;
  24. };
  25. //Define our own treap_node_traits
  26. struct my_treap_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. { bool operator()(const my_node *a, const my_node *b) { return a->int_ < b->int_; } };
  40. struct node_ptr_priority
  41. { bool operator()(const my_node *a, const my_node *b) { return a->prio_ < b->prio_;} };
  42. int main()
  43. {
  44. typedef boost::intrusive::treap_algorithms<my_treap_node_traits> algo;
  45. my_node header, two(2, 5), three(3, 1);
  46. //Create an empty treap 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(), node_ptr_priority());
  51. //Now insert node "three" in the tree using the sorting functor
  52. algo::insert_equal_lower_bound(&header, &three, node_ptr_compare(), node_ptr_priority());
  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, node_ptr_priority());
  61. //Erase a node using also the header (faster)
  62. algo::erase(&header, &three, node_ptr_priority());
  63. return 0;
  64. }
  65. //]