doc_any_hook.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2008-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_any_hook
  13. #include <vector>
  14. #include <boost/intrusive/any_hook.hpp>
  15. #include <boost/intrusive/slist.hpp>
  16. #include <boost/intrusive/list.hpp>
  17. using namespace boost::intrusive;
  18. class MyClass : public any_base_hook<> //Base hook
  19. {
  20. int int_;
  21. public:
  22. any_member_hook<> member_hook_; //Member hook
  23. MyClass(int i = 0) : int_(i)
  24. {}
  25. //<-
  26. int get_int() const { return int_; }
  27. //->
  28. };
  29. int main()
  30. {
  31. //Define a base hook option that converts any_base_hook to a slist hook
  32. typedef any_to_slist_hook < base_hook< any_base_hook<> > > BaseSlistOption;
  33. typedef slist<MyClass, BaseSlistOption> BaseSList;
  34. //Define a member hook option that converts any_member_hook to a list hook
  35. typedef any_to_list_hook< member_hook
  36. < MyClass, any_member_hook<>, &MyClass::member_hook_> > MemberListOption;
  37. typedef list<MyClass, MemberListOption> MemberList;
  38. //Create several MyClass objects, each one with a different value
  39. std::vector<MyClass> values;
  40. for(int i = 0; i < 100; ++i){ values.push_back(MyClass(i)); }
  41. BaseSList base_slist; MemberList member_list;
  42. //Now insert them in reverse order in the slist and in order in the list
  43. for(std::vector<MyClass>::iterator it(values.begin()), itend(values.end()); it != itend; ++it)
  44. base_slist.push_front(*it), member_list.push_back(*it);
  45. //Now test lists
  46. BaseSList::iterator bit(base_slist.begin());
  47. MemberList::reverse_iterator mrit(member_list.rbegin());
  48. std::vector<MyClass>::reverse_iterator rit(values.rbegin()), ritend(values.rend());
  49. //Test the objects inserted in the base hook list
  50. for(; rit != ritend; ++rit, ++bit, ++mrit)
  51. if(&*bit != &*rit || &*mrit != &*rit) return 1;
  52. return 0;
  53. }
  54. //]