boost::range_iterator and boost::iterator_range confusion

Could anyone please explain what is the difference between two and when to use what?

range_iterator is used for get type of range iterator in following way:

range_iterator< SomeRange >::type

It simillar in something to std::iterator_traits. For instance, you may get value type from iterator:

std::iterator_traits<int*>::value_type

iterator_range is bridge between ranges and iterators. For instance - you have pair of iterators, and you want pass them to algorithm which only accepts ranges. In that case you can wrap your iterators into range, using iterator_range. Or better - make_iterator_range - it will help to deduce types (like std::make_pair does):

make_iterator_range(iterator1,iterator2)

returns range.

Consider following example:

live demo

#include <boost/range/iterator_range.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/iterator.hpp>
#include <typeinfo>
#include <iostream>
#include <ostream>

using namespace boost;
using namespace std;

struct print
{
    template<typename T>
    void operator()(const T &t) const
    {
        cout << t << " ";
    }
};

int main()
{
    typedef int Array[20];
    cout << typeid( range_iterator<Array>::type ).name() << endl;

    Array arr={11,22,33,44,55,66,77,88};
    boost::for_each( make_iterator_range(arr,arr+5) ,print());
}

Also, it would be nice if you can point me to sample examples where the boost range library is used to know more about it apart from the documentation

For quick summary - check this slides


Generally, you will not use boost::range_iterator directly, as it is a template metafunction which takes the range given (regardless of the type of the range), and returns the type of it's begin()/end() methods.

boost::iterator_range is used to create a new range from a pair of pre-existing iterators. This you will be more likely to use, usually when taking code that is still iterator based and using that to convert to a range.