Difference between irange and counting_range in Boost

What is the difference between irange and counting_range ?

I needed irange to quickly create a number of such numbers:

 auto example = boost::irange(0, 5); /// result is {0, 1, 2, 3, 4} 

But I noticed an example somewhere (lost a link) that speaks instead of counting_range to accomplish the same task. Is there a simple explanation for the difference between the two?

+8
c ++ boost integer range counting
source share
2 answers

The main difference is that irange is a random access range, and counting_range isn "t. counting_range based on Boost.Iterator counting_iterator , which directly uses all the basic operations with integers. Integers in C ++ almost correspond to the concept of an iterator: the only thing what is missing is operator* . counting_iterator provides operator* as an identification operation and forwards everything else to the base type.

Another difference is that irange also supports increments other than 1.

None of them ever materializes the entire range of integers that they iterate over, so both use O (1) memory.

+27
source share

Both irange and counting_range model a random access range for integer types. As indicated in the documentation for counting_range , its iterator category is determined by the following algorithm:

 if (CategoryOrTraversal is not use_default) return CategoryOrTraversal else if (numeric_limits<Incrementable>::is_specialized) return iterator-category(random_access_traversal_tag, Incrementable, const Incrementable&) else return iterator-category(iterator_traversal<Incrementable>::type, Incrementable, const Incrementable&) 

Therefore, for simple ranges such as boost::irange(0, 10) and boost::counting_range(0, 10) , there is no difference (except for the types of each range, of course!).

However, irange also supports iteration with a different step size, for example, boost::irange(0, 10, 2) and counting_range also supports types that only grow and do not fully model the integer.

0
source share

All Articles