doc_positional_insertion.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /////////////////////////////////////////////////////////////////////////////
  2. //
  3. // (C) Copyright Ion Gaztanaga 2009-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_positional_insertion
  13. #include <boost/intrusive/set.hpp>
  14. #include <vector>
  15. #include <functional>
  16. #include <cassert>
  17. using namespace boost::intrusive;
  18. //A simple class with a set hook
  19. class MyClass : public set_base_hook<>
  20. {
  21. public:
  22. int int_;
  23. MyClass(int i) : int_(i) {}
  24. friend bool operator< (const MyClass &a, const MyClass &b)
  25. { return a.int_ < b.int_; }
  26. friend bool operator> (const MyClass &a, const MyClass &b)
  27. { return a.int_ > b.int_; }
  28. };
  29. int main()
  30. {
  31. //Create some ORDERED elements
  32. std::vector<MyClass> values;
  33. for(int i = 0; i < 100; ++i) values.push_back(MyClass(i));
  34. { //Data is naturally ordered in the vector with the same criteria
  35. //as multiset's comparison predicate, so we can just push back
  36. //all elements, which is more efficient than normal insertion
  37. multiset<MyClass> mset;
  38. for(int i = 0; i < 100; ++i) mset.push_back(values[i]);
  39. //Now check orderd invariant
  40. multiset<MyClass>::const_iterator next(mset.cbegin()), it(next++);
  41. for(int i = 0; i < 99; ++i, ++it, ++next) assert(*it < *next);
  42. }
  43. { //Now the correct order for the set is the reverse order
  44. //so let's push front all elements
  45. multiset<MyClass, compare< std::greater<MyClass> > > mset;
  46. for(int i = 0; i < 100; ++i) mset.push_front(values[i]);
  47. //Now check orderd invariant
  48. multiset<MyClass, compare< std::greater<MyClass> > >::
  49. const_iterator next(mset.cbegin()), it(next++);
  50. for(int i = 0; i < 99; ++i, ++it, ++next) assert(*it > *next);
  51. }
  52. { //Now push the first and the last and insert the rest
  53. //before the last position using "insert_before"
  54. multiset<MyClass> mset;
  55. mset.insert_before(mset.begin(), values[0]);
  56. multiset<MyClass>::const_iterator pos =
  57. mset.insert_before(mset.end(), values[99]);
  58. for(int i = 1; i < 99; ++i) mset.insert_before(pos, values[i]);
  59. //Now check orderd invariant
  60. multiset<MyClass>::const_iterator next(mset.cbegin()), it(next++);
  61. for(int i = 0; i < 99; ++i, ++it, ++next) assert(*it < *next);
  62. }
  63. return 0;
  64. }
  65. //]