doc_sg_set.cpp 2.5 KB

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