Boost logo

Boost :

Subject: Re: [boost] [iterators] how about an identity_iterator or generate_iterator?
From: Jeff Flinn (TriumphSprint2000_at_[hidden])
Date: 2008-12-12 08:01:23


Dean Michael Berris wrote:
> Hi,
>
> Has anybody found a need for an "identity_iterator"? Something that
> you can initialize to a value and returns that value every time it's
> referenced? It could model a random access iterator, and a default
> constructed version will mark an "end" of the identity_iterator.
>
> Something to the effect of:
>
> template <class Type>
> struct identity_iterator {
> identity_iterator(size_t count = 0) : v_(), count_(count) {}
> identity_iterator(const identity_iterator & o) : v_(o.v_), count_(o.count_) {}
> Type operator*() { return v_; }
> identity_iterator & operator++() { ++count_; *this; }
> identity_iterator & operator++(int) { ++count_; *this; }
> bool operator==(identity_iterator const & rhs) {
> return (this->count_ == rhs.count_);
> }
> bool operator<(identity_iterator const & rhs) {
> return (this->count_ < rhs.count_);
> }
> // ... and other required iterator nested types
> private:
> Type v_;
> size_t count_;
> };

How about:

template< typename T >
class identity_iterator
: public boost::iterator_facade< identity_iterator<T>, T
                                , boost::forward_traversal_tag, const T&>
{
public:
     identity_iterator(const T& value, int index)
     : m_value(value), m_index(index) {}

private: // virtual overrides
     friend class boost::iterator_core_access;

     void increment() { ++m_index; }

     const T& dereference() const { return m_value; }
     bool equal(literal_iterator<T> const& rhs) const
     {
        return m_index == rhs.m_index;
     }

private:
     T m_value;
     int m_index;
};

The index allows use with algorithms where and end iterator is req'd.

>
> Or even a "generate_iterator" which takes a nullary function object of
> signature "tuple<bool, T>()" where bool indicates whether it's at the
> end? It can be modeled as an input iterator. Something like:
>
> template <class T>
> struct generate_iterator {
> generate_iterator() : f_(), at_end(true) { }
> generate_iterator(function<tuple<bool, T>() > f) : f_(f), at_end(false) { }
> // copy constructor, swap, assignment, etc.
> T operator* () {
> T return_;
> tie(at_end, return_) = f_();
> return return_;
> }
> // other required nested types
> private:
> function<tuple<bool, T>()> f_;
> bool at_end;
> };
>
> Or is there already something out there which allows these iterator semantics?
>

See:
http://www.boost.org/doc/libs/1_37_0/libs/iterator/doc/function_output_iterator.html

Jeff


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