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