doc_list.cpp 2.2 KB

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