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_avl_set_code
13 #include <boost/intrusive/avl_set.hpp>
14 #include <vector>
15 #include <functional>
16 #include <cassert>
17
18 using namespace boost::intrusive;
19
20 //This is a base hook optimized for size
21 class MyClass : public avl_set_base_hook<optimize_size<true> >
22 {
23 int int_;
24
25 public:
26 //This is a member hook
27 avl_set_member_hook<> member_hook_;
28
MyClass(int i)29 MyClass(int i)
30 : int_(i)
31 {}
operator <(const MyClass & a,const MyClass & b)32 friend bool operator< (const MyClass &a, const MyClass &b)
33 { return a.int_ < b.int_; }
operator >(const MyClass & a,const MyClass & b)34 friend bool operator> (const MyClass &a, const MyClass &b)
35 { return a.int_ > b.int_; }
operator ==(const MyClass & a,const MyClass & b)36 friend bool operator== (const MyClass &a, const MyClass &b)
37 { return a.int_ == b.int_; }
38 };
39
40 //Define an avl_set using the base hook that will store values in reverse order
41 typedef avl_set< MyClass, compare<std::greater<MyClass> > > BaseSet;
42
43 //Define an multiset using the member hook
44 typedef member_hook<MyClass, avl_set_member_hook<>, &MyClass::member_hook_> MemberOption;
45 typedef avl_multiset< MyClass, MemberOption> MemberMultiset;
46
main()47 int main()
48 {
49 typedef std::vector<MyClass>::iterator VectIt;
50
51 //Create several MyClass objects, each one with a different value
52 std::vector<MyClass> values;
53 for(int i = 0; i < 100; ++i) values.push_back(MyClass(i));
54
55 BaseSet baseset;
56 MemberMultiset membermultiset;
57
58 //Check that size optimization is activated in the base hook
59 assert(sizeof(avl_set_base_hook<optimize_size<true> >) == 3*sizeof(void*));
60 //Check that size optimization is deactivated in the member hook
61 assert(sizeof(avl_set_member_hook<>) > 3*sizeof(void*));
62
63 //Now insert them in the sets
64 for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it){
65 baseset.insert(*it);
66 membermultiset.insert(*it);
67 }
68
69 //Now test avl_sets
70 {
71 BaseSet::reverse_iterator rbit(baseset.rbegin());
72 MemberMultiset::iterator mit(membermultiset.begin());
73 VectIt it(values.begin()), itend(values.end());
74
75 //Test the objects inserted in the base hook avl_set
76 for(; it != itend; ++it, ++rbit)
77 if(&*rbit != &*it) return 1;
78
79 //Test the objects inserted in the member hook avl_set
80 for(it = values.begin(); it != itend; ++it, ++mit)
81 if(&*mit != &*it) return 1;
82 }
83 return 0;
84 }
85 //]
86