doc_bucket_traits.cpp 2.3 KB

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