Friday, April 8, 2011

Numerical range iterators in boost?

I'm aware of the range iterators in boost, and as for this reference, it seems there should be an easy way of doing what I want, but it's not obvious to me.

Say I want to represent a numerical range, 0 to 100 (inclusive or not), say range(0,100). I would like to do something like:

for_each(range<int>(0,100).begin(), range<int>(0,100).end(), do_something);

where do_something is a functor. This iterators shouldn't have the overhead of having an underneath vector or something like this, but to just offer a sequence of integers. Is this possible with the range implementation in boost? Possible at all with normal, standard STL iterators?

From stackoverflow
  • boost::counting_iterator

    #include <boost/iterator/counting_iterator.hpp>
    
    std::for_each( boost::counting_iterator<int>(0),
                   boost::counting_iterator<int>(100),
                   do_something );
    
    Diego Sevilla : Thank you! Exactly what I wanted... Don't know how I missed it searching through the boost libraries... :)
  • Yes, it is possible. It just seems boost::range doesn't have support for it out of the box, but you can

    • use boost::counting_iterator, which does just what you want
    • implement a number-like object whose operator*() would return a number, and use that as an iterator for range

0 comments:

Post a Comment