简体   繁体   中英

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?

boost::counting_iterator

#include <boost/iterator/counting_iterator.hpp>

std::for_each( boost::counting_iterator<int>(0),
               boost::counting_iterator<int>(100),
               do_something );

Just to add to the other answers if you're coming from a C++11 perspective - if you'd rather use modern for-each loops, you can do this even more cleanly with boost counting_range :

#include <boost/range/counting_range.hpp>

for(auto const &i : boost::counting_range(0, 10)) {
  std::cout << i;
}

Outputs:

0123456789

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM