Boost logo

Boost :

From: Ion Gaztañaga (igaztanaga_at_[hidden])
Date: 2006-04-09 15:21:28


> You haven't really explained what this thing is supposed to be doing.
> As far as I can tell from the code, it dereferences to the same
> location at each position. If that's really what you intend, you
> ought to do something to ensure that its iterator category doesn't
> indicate it satisfies forward iterator requirements.

A pair of "range_from_ref_iterator" simulates a pair of random access
iterators that point to an array of N identical values.

Suppose:

    range_from_ref_iterator<T>(val, N);

is a iterator to the beginning of a simulated array of N equal elements
with "val" value.

    range_from_ref_iterator<T>();

is a "end" iterator to the end of the array. If you have a function
taking a pair of iterators:

template <class InpIt>
void do_something(InpIt beg, InpIt end);

And you want to simulate it with a range of N equal input values, you
can write:

    std::vector<T> values(N, val);
    std::vector<T>::const_iterator beg = values.begin(),
                                   end = values.end()
    do_something(beg, end);

but it's more efficient to write:

    T val;
    do_something(range_from_ref_iterator<const T>(val, N),
                 range_from_ref_iterator<const T>());

range_from_ref_iterator basically stores a pointer to the value and an
internal count. The end iterator has a 0 count. The internal count is
decremented when incrementing the iterator and operator*() always
returns a reference to "val".

Since range_from_ref_iterator is a random traversal iterator the
function taking iteratorscan optimize the code as if it was an array
(for example in vectors when reallocating internal storage).

Obviously, maybe is only useful with const values because inside an
iteration the source can be modified and in the rest of the iterations
the value would be different from original value, and external "val"
value would be also modified. Maybe even this modification could be
useful, who knows, as an accumulation effect. But I wanted it to
simulate a constant N element array of identical values.

> Seems like a reasonable idea, but I'm not sure whether it's useful
> enough to be included. I'd definitely call it something other than
> range_from_ref_iterator, though. constant_iterator or something like
> that seems appropriate.

constant_iterator seems good, because I'm thinking that maybe it has
sense only to store a constant reference that can't be modified, so

    constant_iterator<T>(val, T);

would return a const reference to val every iteration instead of a
non-const reference.

Ion


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