boost::range_iterator and boost::iterator_range confusion
Asked Answered
M

2

12

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.

Mcelrath answered 8/11, 2012 at 10:11 Comment(0)
R
12

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

Rainproof answered 8/11, 2012 at 13:43 Comment(0)
B
4

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.

Barbarian answered 8/11, 2012 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.