doc_slist.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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_slist_code
  13. #include <boost/intrusive/slist.hpp>
  14. #include <vector>
  15. using namespace boost::intrusive;
  16. //This is a base hook
  17. class MyClass : public slist_base_hook<>
  18. {
  19. int int_;
  20. public:
  21. //This is a member hook
  22. slist_member_hook<> member_hook_;
  23. MyClass(int i)
  24. : int_(i)
  25. {}
  26. //<-
  27. int get_int() const { return int_; }
  28. //->
  29. };
  30. //Define an slist that will store MyClass using the public base hook
  31. typedef slist<MyClass> BaseList;
  32. //Define an slist that will store MyClass using the public member hook
  33. typedef member_hook<MyClass, slist_member_hook<>, &MyClass::member_hook_> MemberOption;
  34. typedef slist<MyClass, MemberOption> MemberList;
  35. int main()
  36. {
  37. typedef std::vector<MyClass>::iterator VectIt;
  38. typedef std::vector<MyClass>::reverse_iterator VectRit;
  39. //Create several MyClass objects, each one with a different value
  40. std::vector<MyClass> values;
  41. for(int i = 0; i < 100; ++i) values.push_back(MyClass(i));
  42. BaseList baselist;
  43. MemberList memberlist;
  44. //Now insert them in the reverse order in the base hook list
  45. for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it)
  46. baselist.push_front(*it);
  47. //Now insert them in the same order as in vector in the member hook list
  48. for(BaseList::iterator it(baselist.begin()), itend(baselist.end())
  49. ; it != itend; ++it){
  50. memberlist.push_front(*it);
  51. }
  52. //Now test lists
  53. {
  54. BaseList::iterator bit(baselist.begin());
  55. MemberList::iterator mit(memberlist.begin());
  56. VectRit rit(values.rbegin()), ritend(values.rend());
  57. VectIt it(values.begin()), itend(values.end());
  58. //Test the objects inserted in the base hook list
  59. for(; rit != ritend; ++rit, ++bit)
  60. if(&*bit != &*rit) return 1;
  61. //Test the objects inserted in the member hook list
  62. for(; it != itend; ++it, ++mit)
  63. if(&*mit != &*it) return 1;
  64. }
  65. return 0;
  66. }
  67. //]