Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 569
polapts Avatar asked Nov 08 '12 10:11

polapts


2 Answers

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.

like image 104
Dave S Avatar answered Sep 22 '22 03:09

Dave S


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

like image 42
Evgeny Panasyuk Avatar answered Sep 23 '22 03:09

Evgeny Panasyuk