Boost logo

Boost :

From: Douglas Gregor (gregod_at_[hidden])
Date: 2001-06-30 13:03:40


Hello all,
        I've written a simple iterator adaptor that caches the result of
dereferencing the underlying iterator. This sort of adaptor is essential to
make the transform_iterator adaptor standards conforming.
        Consider, for instance, using std::max_element on a set of input iterators.
One would expect that dereferencing the result of a std::max_element call
will return the maximal value. However, if side effects are present in the
dereferencing of the underlying input iterators. Using the input caching
iterator adaptor, max_element works as expected.
        The code, documentation, and test for the input caching iterator is in the
vault at:
http://groups.yahoo.com/group/boost/files/input_cache_iter.zip
        
        The policy is short enough that I'll post it here as well for discussion.

        If there is sufficient interest, I'd like to integrate this iterator adaptor
with the iterator adaptors library.

        Doug

  template<typename T>
  class input_caching_policy : public default_iterator_policies {
  public:
    template <class BaseType>
    void initialize(BaseType&)
    {
      result_initialized = false;
    }

    template <class Reference, class BaseType>
    Reference dereference(type<Reference>, const BaseType& x) const
    {
      if (!result_initialized) {
        result = *x;
        result_initialized = true;
      }

      return result;
    }

    template <class BaseType>
    void increment(BaseType& x)
    {
      result_initialized = false;
      ++x;
    }

    template <class BaseType>
    void decrement(BaseType& x)
    {
      --x;
      result_initialized = false;
    }

    template <class BaseType, class DifferenceType>
    void advance(BaseType& x, DifferenceType n)
    {
      x += n;
      result_initialized = false;
    }

  private:
    mutable T result;
    mutable bool result_initialized;
  };


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk