doc_splay_set.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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_splay_set_code
  13. #include <boost/intrusive/splay_set.hpp>
  14. #include <vector>
  15. #include <functional>
  16. using namespace boost::intrusive;
  17. class mytag;
  18. class MyClass
  19. : public bs_set_base_hook<>
  20. {
  21. int int_;
  22. public:
  23. //This is a member hook
  24. bs_set_member_hook<> member_hook_;
  25. MyClass(int i)
  26. : int_(i)
  27. {}
  28. friend bool operator< (const MyClass &a, const MyClass &b)
  29. { return a.int_ < b.int_; }
  30. friend bool operator> (const MyClass &a, const MyClass &b)
  31. { return a.int_ > b.int_; }
  32. friend bool operator== (const MyClass &a, const MyClass &b)
  33. { return a.int_ == b.int_; }
  34. };
  35. //Define a set using the base hook that will store values in reverse order
  36. typedef splay_set< MyClass, compare<std::greater<MyClass> > > BaseSplaySet;
  37. //Define an multiset using the member hook
  38. typedef member_hook<MyClass, bs_set_member_hook<>, &MyClass::member_hook_> MemberOption;
  39. typedef splay_multiset< MyClass, MemberOption> MemberSplayMultiset;
  40. int main()
  41. {
  42. typedef std::vector<MyClass>::iterator VectIt;
  43. //Create several MyClass objects, each one with a different value
  44. std::vector<MyClass> values;
  45. for(int i = 0; i < 100; ++i) values.push_back(MyClass(i));
  46. BaseSplaySet baseset;
  47. MemberSplayMultiset membermultiset;
  48. //Insert values in the container
  49. for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it){
  50. baseset.insert(*it);
  51. membermultiset.insert(*it);
  52. }
  53. //Now test sets
  54. {
  55. BaseSplaySet::reverse_iterator rbit(baseset.rbegin());
  56. MemberSplayMultiset::iterator mit(membermultiset.begin());
  57. VectIt it(values.begin()), itend(values.end());
  58. //Test the objects inserted in the base hook set
  59. for(; it != itend; ++it, ++rbit){
  60. if(&*rbit != &*it) return 1;
  61. }
  62. //Test the objects inserted in member and binary search hook sets
  63. for(it = values.begin(); it != itend; ++it, ++mit){
  64. if(&*mit != &*it) return 1;
  65. }
  66. }
  67. return 0;
  68. }
  69. //]