• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_bucket_traits
13 #include <boost/intrusive/unordered_set.hpp>
14 #include <boost/functional/hash.hpp>
15 #include <vector>
16 
17 using namespace boost::intrusive;
18 
19 //A class to be inserted in an unordered_set
20 class MyClass : public unordered_set_base_hook<>
21 {
22    int int_;
23 
24    public:
MyClass(int i=0)25    MyClass(int i = 0) : int_(i)
26    {}
27 
operator ==(const MyClass & l,const MyClass & r)28    friend bool operator==(const MyClass &l, const MyClass &r)
29       {  return l.int_ == r.int_;   }
hash_value(const MyClass & v)30    friend std::size_t hash_value(const MyClass &v)
31       {  return boost::hash_value(v.int_); }
32 };
33 
34 //Define the base hook option
35 typedef base_hook< unordered_set_base_hook<> >     BaseHookOption;
36 
37 //Obtain the types of the bucket and the bucket pointer
38 typedef unordered_bucket<BaseHookOption>::type     BucketType;
39 typedef unordered_bucket_ptr<BaseHookOption>::type BucketPtr;
40 
41 //The custom bucket traits.
42 class custom_bucket_traits
43 {
44    public:
45    static const int NumBuckets = 100;
46 
custom_bucket_traits(BucketPtr buckets)47    custom_bucket_traits(BucketPtr buckets)
48       :  buckets_(buckets)
49    {}
50 
51    //Functions to be implemented by custom bucket traits
bucket_begin() const52    BucketPtr   bucket_begin() const {  return buckets_;  }
bucket_count() const53    std::size_t bucket_count() const {  return NumBuckets;}
54 
55    private:
56    BucketPtr buckets_;
57 };
58 
59 //Define the container using the custom bucket traits
60 typedef unordered_set<MyClass, bucket_traits<custom_bucket_traits> > BucketTraitsUset;
61 
main()62 int main()
63 {
64    typedef std::vector<MyClass>::iterator VectIt;
65    std::vector<MyClass> values;
66 
67    //Fill values
68    for(int i = 0; i < 100; ++i)  values.push_back(MyClass(i));
69 
70    //Now create the bucket array and the custom bucket traits object
71    BucketType buckets[custom_bucket_traits::NumBuckets];
72    custom_bucket_traits btraits(buckets);
73 
74    //Now create the unordered set
75    BucketTraitsUset uset(btraits);
76 
77    //Insert the values in the unordered set
78    for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it)
79       uset.insert(*it);
80 
81    return 0;
82 }
83 //]
84