RandomIter.h
Go to the documentation of this file.
1 #ifndef WIRECELLUTIL_RANDOMITER
2 #define WIRECELLUTIL_RANDOMITER
3 
4 #include <boost/iterator/iterator_categories.hpp>
5 #include <boost/iterator/iterator_facade.hpp>
6 
7 namespace WireCell {
8 
9 template <typename Container, typename Value>
10 struct RandomIter : public boost::iterator_facade<
11  RandomIter<Container, Value>,
12  Value,
13  boost::random_access_traversal_tag
14  >
15 {
16  // Constructor for begin()
17  explicit RandomIter(Container& array)
18  : m_array(array)
19  , m_index(0)
20  {}
21 
22  // Constructor for end(), bool is just a maker
23  explicit RandomIter(bool, Container& array)
24  : m_array(array)
25  , m_index(array.size())
26  {}
27 
28 private:
30 
31  Container & m_array;
32  int m_index;
33 
35  {
36  return this->m_index == other.m_index;
37  }
38 
39  typedef boost::iterator_facade<
41  Value,
42  boost::random_access_traversal_tag
43  > facade;
44  typename facade::difference_type distance_to(RandomIter const& other) const {
45  return other.m_index - this->m_index;
46  }
47 
48  void advance(typename facade::difference_type n)
49  {
50  m_index += n;
51  if (m_index >= (int)m_array.size() || m_index < 0) {
52  m_index = m_array.size();
53  }
54  }
55 
56  void increment() {
57  advance(1);
58  }
59 
60  void decrement() {
61  advance(-1);
62  }
63 
64  // const and non-const dereference of this iterator
65  Value& dereference() const {
66  return m_array.at(m_index);
67  }
68 };
69 
70 }
71 
72 #endif
void advance(typename facade::difference_type n)
Definition: RandomIter.h:48
Container & m_array
Definition: RandomIter.h:31
RandomIter(bool, Container &array)
Definition: RandomIter.h:23
decltype(auto) constexpr size(T &&obj)
ADL-aware version of std::size.
Definition: StdUtils.h:87
auto array(Array const &a)
Returns a manipulator which will print the specified array.
Definition: DumpUtils.h:228
GenericValue< UTF8<> > Value
GenericValue with UTF8 encoding.
Definition: document.h:2106
boost::iterator_facade< RandomIter< Container, Value >, Value, boost::random_access_traversal_tag > facade
Definition: RandomIter.h:43
friend class boost::iterator_core_access
Definition: RandomIter.h:29
bool equal(RandomIter< Container, Value > const &other) const
Definition: RandomIter.h:34
Value & dereference() const
Definition: RandomIter.h:65
Definition: Main.h:22
facade::difference_type distance_to(RandomIter const &other) const
Definition: RandomIter.h:44
RandomIter(Container &array)
Definition: RandomIter.h:17
std::size_t n
Definition: format.h:3399