TermOx
filter_iterator.hpp
1 #ifndef TERMOX_COMMON_FILTER_ITERATOR_HPP
2 #define TERMOX_COMMON_FILTER_ITERATOR_HPP
3 #include <iterator>
4 #include <utility>
5 
6 namespace ox {
7 
9 template <typename Iter, typename Iter_end, typename F>
11  public:
12  using iterator_category = std::forward_iterator_tag;
13  using value_type = typename Iter::value_type;
14  using difference_type = typename Iter::difference_type;
15  using pointer = typename Iter::pointer;
16  using reference = typename Iter::reference;
17 
18  public:
20 
21  Filter_iterator(Iter const it, Iter_end const end, F&& predicate)
22  : it_{it}, end_{end}, predicate_{std::forward<F>(predicate)}
23  {
24  this->increment_if_invalid();
25  }
26 
27  public:
28  auto operator++() -> Filter_iterator&
29  {
30  this->increment();
31  return *this;
32  }
33 
34  [[nodiscard]] auto operator++(int) -> Filter_iterator
35  {
36  auto copy = *this;
37  copy.increment();
38  return copy;
39  }
40 
41  [[nodiscard]] auto operator*() const -> auto& { return *it_; }
42 
43  [[nodiscard]] auto operator==(Filter_iterator const& other) const -> bool
44  {
45  return it_ == other.it_;
46  }
47 
48  [[nodiscard]] auto operator!=(Filter_iterator const& other) const -> bool
49  {
50  return it_ != other.it_;
51  }
52 
53  template <typename T>
54  [[nodiscard]] auto operator==(T const& other) const -> bool
55  {
56  return it_ == other;
57  }
58 
59  template <typename T>
60  [[nodiscard]] auto operator!=(T const& other) const -> bool
61  {
62  return it_ != other;
63  }
64 
65  private:
66  Iter it_;
67  Iter_end const end_;
68  F predicate_;
69 
70  private:
71  void increment_if_invalid()
72  {
73  while ((it_ != end_) && !predicate_(*it_))
74  ++it_;
75  }
76 
77  void increment()
78  {
79  do {
80  ++it_;
81  } while ((it_ != end_) && !predicate_(*it_));
82  }
83 };
84 
85 } // namespace ox
86 #endif // TERMOX_COMMON_FILTER_ITERATOR_HPP
operator++ skips underlying elements of it that do not satisfy predicate.
Definition: filter_iterator.hpp:10
Filter_iterator(Iter const it, Iter_end const end, F &&predicate)
Pass in the iterator to begin at, end iter, and predicate to test with.
Definition: filter_iterator.hpp:21