Boost C++ Libraries Home Libraries People FAQ More


Class sub_range

The sub_range class inherits all its functionality from the iterator_range class. The sub_range class is often easier to use because one must specify the Forward Range template argument instead of an iterator. Moreover, the sub_range class can propagate constness since it knows what a corresponding const_iterator is.


namespace boost
    template< class ForwardRange >
    class sub_range : public iterator_range< typename range_iterator<ForwardRange>::type >
        typedef typename range_value<ForwardRange>::type value_type;
        typedef typename range_iterator<ForwardRange>::type iterator;
        typedef typename range_iterator<const ForwardRange>::type  const_iterator;
        typedef typename range_difference<ForwardRange>::type difference_type;
        typedef typename range_size<ForwardRange>::type size_type;
        typedef typename range_reference<ForwardRange>::type reference;
        typedef typename range_reference<const ForwardRange>::type const_reference;

    public: // construction, assignment

        template< class ForwardTraversalIterator >
        sub_range( ForwardTraversalIterator Begin, ForwardTraversalIterator End );

        template< class ForwardRange2 >
        sub_range( ForwardRange2& r );

        template< class ForwardRange2 >
        sub_range( const Range2& r );

        template< class ForwardRange2 >
        sub_range& operator=( ForwardRange2& r );

        template< class ForwardRange2 >
        sub_range& operator=( const ForwardRange2& r );

        // iterator accessors
        const_iterator begin() const;
        iterator begin();
        const_iterator end() const;
        iterator end();

        reference front();
        const_reference front() const;

        sub_range& advance_begin(difference_type n);
        sub_range& advance_end(difference_type n);

        // If traversal >= bidirectional:
        reference back();
        const_reference back();

        // If traversal >= random-access:
        reference operator[](difference_type n);
        const_reference operator[](difference_type n) const;

        // rest of interface inherited from iterator_range

} // namespace 'boost'

The class should be trivial to use as seen below. Imagine that we have an algorithm that searches for a sub-string in a string. The result is an iterator_range, that delimits the match. We need to store the result from this algorithm. Here is an example of how we can do it with and without sub_range

std::string str("hello");
iterator_range<std::string::iterator> ir = find_first( str, "ll" );
sub_range<std::string>               sub = find_first( str, "ll" );