Assuming you are not in control of the vector<int> interface, for example. because it’s actually std::vector<int> , the first thing you want to do is change the way you get custom iterators. That is, instead of writing
for (vector<int>::my_iterator it = v.my_begin(); it != v.my_ned(); ++it)
would you use
for (my_iterator it(my_begin(v)), end(my_end(v)); it != end; ++it)
You can create a modified interface for the custom container, but it's a big fish to fry. Creating an input iterator now essentially boils down to creating a suitable wrapper for the main iterator. It might look something like this:
template <typename InIt, Pred> struct my_iterator { typedef typename std::iterator_traits<InIt>::value_type value_type; typedef typename std::iterator_traits<InIt>::difference_type difference_type; typedef typename std::iterator_traits<InIt>::reference reference; typedef typename std::iterator_traits<InIt>::pointer pointer; my_iterator(InIt it, InIt end, Pred pred): it_(it), end_(end), pred_(pred) {} bool operator== (my_iterator const& other) const { reutrn this->it_ == other.it_; } bool operator!= (my_iterator const& other) const { return !(*this == other); } reference operator*() { return *this->it_; } pointer operator->() { return this->it_; } my_iterator& operator++() { this->it_ = std::find_if(this->it_, this->end_, this->pred_); return *this; } my_iterator operator++(int) { my_iterator rc(*this); this->operator++(); return rc; } private: InIt it_, end_; Pred pred_;
The functions my_begin() and my_end() will then create a suitable object of this type. One approach to avoid having to write this is to take a look at the Boost iterator adapters: there should be something suitable.
source share