Numerical range iterators in boost?

2019-02-06 06:45发布

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?

3条回答
Ridiculous、
2楼-- · 2019-02-06 07:36

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

查看更多
叼着烟拽天下
3楼-- · 2019-02-06 07:42

boost::counting_iterator

#include <boost/iterator/counting_iterator.hpp>

std::for_each( boost::counting_iterator<int>(0),
               boost::counting_iterator<int>(100),
               do_something );
查看更多
在下西门庆
4楼-- · 2019-02-06 07:47

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
查看更多
登录 后发表回答