c++boostboost-range

boost::range_iterator and boost::iterator_range confusion


I have been going through the boost::range library and noticed boost::range_iterator and boost::iterator_range. I am confused with these terms here. Could anyone please explain what is the difference between two and when to use what? 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.


Solution

  • 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