您好,欢迎来到星星旅游。
搜索
您的当前位置:首页boost_range

boost_range

来源:星星旅游
Boost.Range Documentation

Copyright © 2003 -2007 Thorsten Ottosen

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy athttp://www.boost.org/LICENSE_1_0.txt)

Table of Contents

Introduction..........................................................................................................................................................1Range Concepts.....................................................................................................................................................3

Overview......................................................................................................................................................3Single Pass Range..........................................................................................................................................3Forward Range..............................................................................................................................................5Bidirectional Range........................................................................................................................................6Random Access Range....................................................................................................................................7Concept Checking..........................................................................................................................................7Reference.............................................................................................................................................................8

Overview......................................................................................................................................................8Synopsis.......................................................................................................................................................9Semantics...................................................................................................................................................11Extending the library.....................................................................................................................................15Utilities..............................................................................................................................................................18

Class iterator_range................................................................................................................................19Class sub_range.........................................................................................................................................22Terminology and style guidelines............................................................................................................................24Library Headers...................................................................................................................................................25Examples............................................................................................................................................................26Portability...........................................................................................................................................................26FAQ...................................................................................................................................................................26History and Acknowledgement................................................................................................................................27Boost.Range is a collection of concepts and utilities that are particularly useful for specifying and implementing generic algorithms.

Introduction

Generic algorithms have so far been specified in terms of two or more iterators. Two iterators would together form a range of valuesthat the algorithm could work on. This leads to a very general interface, but also to a somewhat clumsy use of the algorithms withredundant specification of container names. Therefore we would like to raise the abstraction level for algorithms so they specifytheir interface in terms of Ranges as much as possible.

The most common form of ranges we are used to work with is standard library containers. However, one often finds it desirable toextend that code to work with other types that offer enough functionality to satisfy the needs of the generic code if a suitable layerof indirection is applied . For example, raw arrays are often suitable for use with generic code that works with containers, provideda suitable adapter is used. Likewise, null terminated strings can be treated as containers of characters, if suitably adapted.This library therefore provides the means to adapt standard-like containers, null terminated strings, std::pairs of iterators, andraw arrays (and more), such that the same generic code can work with them all. The basic idea is to add another layer of indirectionusing metafunctions and free-standing functions so syntactic and/or semantic differences can be removed.The main advantages are

•simpler implementation and specification of generic range algorithms•more flexible, compact and maintainable client code

1

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

•correct handling of null-terminated strings

Warning: support for null-terminated strings is deprecated and will disappear in the next Boost release(1.34).

•safe use of built-in arrays (for legacy code; why else would you use built-in arrays?)Below are given a small example (the complete example can be found here ):

//

// example: extracting bounds in a generic algorithm//

template

inlinetypename boost::range_iterator< ForwardReadableRange >::typefind( ForwardReadableRange& c,const T& value ){

return std::find( boost::begin( c ), boost::end( c ), value );}

template

inlinetypename boost::range_const_iterator< ForwardReadableRange >::typefind(const ForwardReadableRange& c,const T& value ){

return std::find( boost::begin( c ), boost::end( c ), value );}

//

// replace first value and return its index//

template

inlinetypename boost::range_size< ForwardReadableWriteableRange >::type

my_generic_replace( ForwardReadableWriteableRange& c,const T& value,const T& replacement ){

typename boost::range_iterator< ForwardReadableWriteableRange >::type found = find( c, value );

if( found != boost::end( c ))

*found = replacement;

return std::distance( boost::begin( c ), found );}

//

// usage//

constint N =5;

std::vector my_vector;

int values[]={1,2,3,4,5,6,7,8,9};

my_vector.assign( values, boost::end( values ));typedef std::vector::iterator iterator;

std::pair my_view( boost::begin( my_vector ),

boost::begin( my_vector )+ N );char str_val[]=\"a string\";char* str = str_val;

2

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

std::cout << my_generic_replace( my_vector,4,2);std::cout << my_generic_replace( my_view,4,2);std::cout << my_generic_replace( str,'a','b');// prints '3', '5' and '0'

By using the free-standing functions and metafunctions, the code automatically works for all the types supported by this library;now and in the future. Notice that we have to provide two version of find() since we cannot forward a non-const rvalue with ref-erence arguments (see this article about The Forwarding Problem ).

Range Concepts

Overview

A Range is a concept similar to the STL Container concept. A Range provides iterators for accessing a half-open range[first,one_past_last) of elements and provides information about the number of elements in the Range. However, a Rangehas fewer requirements than a Container.

The motivation for the Range concept is that there are many useful Container-like types that do not meet the full requirements ofContainer, and many algorithms that can be written with this reduced set of requirements. In particular, a Range does not necessarily•own the elements that can be accessed through it,•have copy semantics,

Because of the second requirement, a Range object must be passed by (const or non-const) reference in generic code.

The operations that can be performed on a Range is dependent on the traversal category of the underlying iterator type. Thereforethe range concepts are named to reflect which traversal category its iterators support. See also terminology and style guidelines. formore information about naming of ranges.

The concepts described below specifies associated types as metafunctions and all functions as free-standing functions to allow fora layer of indirection.

Single Pass Range

Notation

XA type that is a model of Single Pass Range. a Object of type X.

Description

A range X where boost::range_iterator::type is a model of Single Pass Iterator.

3

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Associated types

Value typeIterator type

boost::range_value::typeboost::range_iterator::type

The type of the object stored in a Range.The type of iterator used to iterate througha Range's elements. The iterator's valuetype is expected to be the Range's valuetype. A conversion from the iterator typeto the const iterator type must exist.A type of iterator that may be used to ex-amine, but not to modify, a Range's ele-ments.

Const iterator type

boost::range_const_iterat-or::type

Valid expressions

The following expressions must be valid.Name

Beginning of range

Expression

boost::begin(a)

Return type

boost::range_iterator::typeif a is mutable,

boost::range_const_iterat-or::type otherwise

boost::range_iterator::typeif a is mutable,

boost::range_const_iterat-or::type otherwise

End of rangeboost::end(a)

Is range empty?boost::empty(a)Convertible to bool

Expression semantics

Expression

boost::begin(a)

Semantics

Returns an iterator pointing to the firstelement in the Range.

Returns an iterator pointing one past thelast element in the Range.

Equivalent to boost::begin(a) ==boost::end(a). (But possibly faster.)

Postcondition

boost::begin(a) is either dereference-

able or past-the-end. It is past-the-end ifand only if boost::size(a) == 0.

boost::end(a) is past-the-end.

boost::end(a)

boost::empty(a)-

Complexity guarantees

All three functions are at most amortized linear time. For most practical purposes, one can expect boost::begin(a), boost::end(a)and boost::empty(a) to be amortized constant time.

4

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Invariants

Valid range

For any Range a, [boost::begin(a),boost::end(a)) isa valid range, that is, boost::end(a) is reachable fromboost::begin(a) in a finite number of increments.An algorithm that iterates through the range [boost::be-gin(a),boost::end(a)) will pass through every elementof a.

Completeness

See also

Container

implementation of metafunctionsimplementation of functions

Forward Range

Notation

XA type that is a model of Forward Range. a Object of type X.

Description

A range X where boost::range_iterator::type is a model of Forward Traversal Iterator.

Refinement of

Single Pass Range

Associated types

Distance type

boost::range_differ-ence::type

A signed integral type used to representthe distance between two of the Range'siterators. This type must be the same asthe iterator's distance type.

An unsigned integral type that can repres-ent any nonnegative value of the Range'sdistance type.

Size typeboost::range_size::type

Valid expressions

NameSize of range

Expression

boost::size(a)

Return type

boost::range_size::type

5

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Expression semantics

Expression

boost::size(a)

Semantics

Returns the size of the Range, that is, itsnumber of elements. Noteboost::size(a) == 0u is equivalentto boost::empty(a).

Postcondition

boost::size(a) >= 0

Complexity guarantees

boost::size(a) is at most amortized linear time.

Invariants

Range size

boost::size(a) is equal to the distance from boost::be-gin(a) to boost::end(a).

See also

implementation of metafunctionsimplementation of functions

Bidirectional Range

Notation

XA type that is a model of Bidirectional Range. a Object of type X.

Description

This concept provides access to iterators that traverse in both directions (forward and reverse). The boost::range_iterat-or::type iterator must meet all of the requirements of Bidirectional Traversal Iterator.

Refinement of

Forward Range

Associated types

Reverse Iterator type

boost::range_reverse_iterat-or::type

The type of iterator used to iterate througha Range's elements in reverse order. Theiterator's value type is expected to be theRange's value type. A conversion fromthe reverse iterator type to the const re-verse iterator type must exist.

A type of reverse iterator that may be usedto examine, but not to modify, a Range'selements.

Const reverse iterator type

boost::range_const_reverse_iter-ator::type

6

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Valid expressions

Name

Beginning of range

Expression

boost::rbegin(a)

Return type

boost::range_re-verse_iterator::typeif a is mutable

boost::range_const_re-verse_iterator::type

Semantics

Equivalent to

boost::range_re-verse_iterat-or::type(boost::end(a)).

otherwise.

End of range

boost::rend(a)

boost::range_re-verse_iterator::typeif a is mutable,

boost::range_const_re-verse_iterator::type

Equivalent to

boost::range_re-verse_iterat-or::type(boost::be-gin(a)).

otherwise.

Complexity guarantees

boost::rbegin(a) has the same complexity as boost::end(a) and boost::rend(a) has the same complexity asboost::begin(a) from Forward Range.

Invariants

Valid reverse range

For any Bidirectional Range a, [boost::rbe-gin(a),boost::rend(a)) is a valid range, that is,boost::rend(a) is reachable from boost::rbegin(a) ina finite number of increments.

An algorithm that iterates through the range[boost::rbegin(a),boost::rend(a)) will pass through everyelement of a`.

Completeness

See also

implementation of metafunctionsimplementation of functions

Random Access Range

Description

A range X where boost::range_iterator::type is a model of Random Access Traversal Iterator.

Refinement of

Bidirectional Range

Concept Checking

Each of the range concepts has a corresponding concept checking class in the file boost/range/concepts.hpp. These classesmay be used in conjunction with the Boost Concept Check library to insure that the type of a template parameter is compatible witha range concept. If not, a meaningful compile time error is generated. Checks are provided for the range concepts related to iteratortraversal categories. For example, the following line checks that the type T models the Forward Range concept.

7

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

function_requires>();

An additional concept check is required for the value access property of the range based on the range's iterator type. For example tocheck for a ForwardReadableRange, the following code is required.

function_requires>(); function_requires<

ReadableIteratorConcept<

typename range_iterator::type>>();

The following range concept checking classes are provided.•Class SinglePassRangeConcept checks for Single Pass Range•Class ForwardRangeConcept checks for Forward Range•Class BidirectionalRangeConcept checks for Bidirectional Range•Class RandomAccessRangeConcept checks for Random Access Range

See also

Range Terminology and style guidelinesIterator concepts

Boost Concept Check library

Reference

Overview

Four types of objects are currently supported by the library:•standard-like containers

•std::pair

•null terminated strings (this includes char[],wchar_t[], char*, and wchar_t*)

Warning: support for null-terminated strings is deprecated and will disappear in the next Boost release(1.34).

•built-in arrays

Even though the behavior of the primary templates are exactly such that standard containers will be supported by default, the require-ments are much lower than the standard container requirements. For example, the utility class iterator_range implements theminimal interface required to make the class a Forward Range.Please also see Range concepts for more details.

8

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Synopsis

namespace boost{

//

// Single Pass Range metafunctions//

templatestruct range_value;templatestruct range_iterator;template

struct range_const_iterator;//

// Forward Range metafunctions//

template

struct range_difference;templatestruct range_size;

//

// Bidirectional Range metafunctions//

template

struct range_reverse_iterator;template

struct range_const_reverse_iterator;//

// Special metafunctions//

template

struct range_result_iterator;

template

struct range_reverse_result_iterator;//

// Single Pass Range functions//

template

typename range_iterator::type begin( T& c );

template

typename range_const_iterator::type begin(const T& c );

template

typename range_iterator::type end( T& c );

9

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

template

typename range_const_iterator::type end(const T& c );templatebool

empty(const T& c );

//

// Forward Range functions//

template

typename range_size::type size(const T& c );

//

// Bidirectional Range functions//

template

typename range_reverse_iterator::type rbegin( T& c );

template

typename range_const_reverse_iterator::type rbegin(const T& c );

template

typename range_reverse_iterator::type rend( T& c );

template

typename range_const_reverse_iterator::type rend(const T& c );

//

// Special const Range functions//

template

typename range_const_iterator::type const_begin(const T& r );

template

typename range_const_iterator::type const_end(const T& r );

template

typename range_const_reverse_iterator::type const_rbegin(const T& r );

10

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

template

typename range_const_reverse_iterator::type const_rend(const T& r );}// namespace 'boost'

Semantics

notationType

XTP

Object

xtp

Describesany type

denotes behavior of the primary templatesdenotes std::pair

A[sz]Char*

as

denotes an array of type A of size szdenotes either char* or wchar_t*

Please notice in tables below that when four lines appear in a cell, the first line will describe the primary template, the second linepairs of iterators, the third line arrays and the last line null-terminated strings.

11

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Metafunctions

Expression

range_value::type

Return type

T::value_type

boost::iterat-or_value::typeAChar

T::iteratorP::first_typeA*Char*

T::const_iteratorP::first_typeconst A*const Char*

T::difference_type

boost::iterator_differ-ence::typestd::ptrdiff_tstd::ptrdiff_tT::size_typestd::size_tstd::size_tstd::size_t

range_const_iterator::type ifX is const

range_iterator::type otherwiseboost::reverse_iterator< type-name range_iterator::type >boost::reverse_iterator< type-name range_const_iterat-or::type >

boost::reverse_iterator< type-name range_result_iterat-or::type >

Complexitycompile time

range_iterator::typecompile time

range_const_iterator::typecompile time

range_difference::typecompile time

range_size::typecompile time

range_result_iterator::typecompile time

range_reverse_iterator::typecompile timecompile time

range_const_reverse_iterat-or::type

range_reverse_result_iterat-or::type

compile time

The special metafunctions range_result_iterator and range_reverse_result_iterator are not part of any Range concept,but they are very useful when implementing certain Range classes like sub_range because of their ability to select iterators basedon constness.

12

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Functions

13

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Expression

begin(x)

Return type

range_result_iterat-or::type

Returns

p.first if p is of typestd::paira if a is an array

s if s is a string literal

boost_range_begin(x) if

Complexityconstant time

that expression would invokea function found by ADLt.begin() otherwise

end(x)

range_result_iterat-or::type

p.second if p is of typestd::pair

a + sz if a is an array of sizeszs +

std::char_traits::length(s ) if s is a Char*

s + sz - 1 if s is a stringliteral of size sz

boost_range_end(x) if that

linear if X is Char* constanttime otherwise

expression would invoke afunction found by ADLt.end() otherwise

empty(x)

bool

begin(x) == end( x )

linear if X is Char*constant time otherwiselinear if X is Char* or ifstd::distance() is linearconstant time otherwise

size(x)range_size::type

std::dis-tance(p.first,p.second)if p is of type std::pairsz if a is an array of size szend(s) - s if s is a stringliteral or a Char*

boost_range_size(x) if

that expression would invokea function found by ADLt.size() otherwise

rbegin(x)

range_reverse_res-ult_iterator::type

range_reverse_res-ult_iterator::type(end(x) )

range_reverse_res-ult_iterator::type(begin(x) )

range_const_iterat-or::type( begin(x))

range_const_iterat-or::type( end(x) )

same as end(x)

rend(x)

range_reverse_res-ult_iterator::type

same as begin(x)

const_begin(x)

range_const_iterat-or::type

same as begin(x)

const_end(x)

range_const_iterat-or::type

same as end(x)

14

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Expression

const_rbegin(x)

Return type

range_const_re-verse_iterator::type

Returns

range_const_re-verse_iterat-or::type( rbegin(x))

range_const_re-verse_iterat-or::type( rend(x) )

Complexitysame as rbegin(x)

const_rend(x)

range_const_re-verse_iterator::type

same as rend(x)

The special const functions are not part of any Range concept, but are very useful when you want to document clearly that your codeis read-only.

Extending the library

Method 1: provide member functions and nested types

This procedure assumes that you have control over the types that should be made conformant to a Range concept. If not, see method2.

The primary templates in this library are implemented such that standard containers will work automatically and so will boost::array.Below is given an overview of which member functions and member types a class must specify to be useable as a certain Rangeconcept.

Member function

begin()end()size()

Related conceptSingle Pass RangeSingle Pass RangeForward Range

Notice that rbegin() and rend() member functions are not needed even though the container can support bidirectional iteration.The required member types are:Member type

iteratorconst_iteratorsize_type

Related conceptSingle Pass RangeSingle Pass RangeForward Range

Again one should notice that member types reverse_iterator and const_reverse_iterator are not needed.

Method 2: provide free-standing functions and specialize metafunctions

This procedure assumes that you cannot (or do not wish to) change the types that should be made conformant to a Range concept.If this is not true, see method 1.

The primary templates in this library are implemented such that certain functions are found via argument-dependent-lookup (ADL).Below is given an overview of which free-standing functions a class must specify to be useable as a certain Range concept. Let xbe a variable (const or mutable) of the class in question.

15

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Function

boost_range_begin(x)boost_range_end(x)boost_range_size(x)

Related conceptSingle Pass RangeSingle Pass RangeForward Range

boost_range_begin() and boost_range_end() must be overloaded for both const and mutable reference arguments.

You must also specialize 3 metafunctions for your type X:Metafunction

boost::range_iteratorboost::range_const_iteratorboost::range_size

Related conceptSingle Pass RangeSingle Pass RangeForward Range

A complete example is given here:

16

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

#include#include

// for std::iterator_traits, std::distance()

namespace Foo{

//

// Our sample UDT. A 'Pair'

// will work as a range when the stored// elements are iterators.//

templatestruct Pair{

T first, last;

};}// namespace 'Foo'

namespace boost{

//

// Specialize metafunctions. We must include the range.hpp header.// We must open the 'boost' namespace.//template

struct range_iterator< Foo::Pair>{

typedef T type;};

template

struct range_const_iterator< Foo::Pair>{//

// Remark: this is defined similar to 'range_iterator'// because the 'Pair' type does not distinguish// between an iterator and a const_iterator.//

typedef T type;};

template

struct range_size< Foo::Pair>{

typedef std::size_t type;};

}// namespace 'boost'

namespace Foo{//

// The required functions. These should be defined in// the same namespace as 'Pair', in this case // in namespace 'Foo'.//

template

inline T boost_range_begin( Pair& x ){

return x.first;

17

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

}

template

inline T boost_range_begin(const Pair& x ){

return x.first;}

template

inline T boost_range_end( Pair& x ){

return x.last;}

template

inline T boost_range_end(const Pair& x ){

return x.last;}

template

inlinetypename boost::range_size< Pair>::type boost_range_size(const Pair& x ){

return std::distance(x.first,x.last);}

}// namespace 'Foo'#include

int main(){

typedef std::vector::iterator iter; std::vector vec;

Foo::Pair pair ={ vec.begin(), vec.end()};const Foo::Pair& cpair = pair;//

// Notice that we call 'begin' etc with qualification. //

iter i = boost::begin( pair ); iter e = boost::end( pair ); i = boost::begin( cpair ); e = boost::end( cpair );

boost::range_size< Foo::Pair>::type s = boost::size( pair ); s = boost::size( cpair );

boost::range_const_reverse_iterator< Foo::Pair>::type ri = boost::rbegin( cpair ), re = boost::rend( cpair );}

Utilities

Having an abstraction that encapsulates a pair of iterators is very useful. The standard library uses std::pair in some circumstances,but that class is cumbersome to use because we need to specify two template arguments, and for all range algorithm purposes wemust enforce the two template arguments to be the same. Moreover, std::pair is hardly self-documentingwhereas more domain specific class names are. Therefore these two classes are provided:•Class iterator_range•Class sub_range

18

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

The iterator_range class is templated on an Forward Traversal Iterator and should be used whenever fairly general code isneeded. The sub_range class is templated on an Forward Range and it is less general, but a bit easier to use since its template argumentis easier to specify. The biggest difference is, however, that a sub_range can propagate constness because it knows what a corres-ponding const_iterator is.

Both classes can be used as ranges since they implement the minimal interface required for this to work automatically.

Class iterator_range

The intention of the iterator_range class is to encapsulate two iterators so they fulfill the Forward Range concept. A few otherfunctions are also provided for convenience.

If the template argument is not a model of Forward Traversal Iterator, one can still use a subset of the interface. In particular, size()requires Forward Traversal Iterators whereas empty() only requires Single Pass Iterators.

Recall that many default constructed iterators are singular and hence can only be assigned, but not compared or incremented oranything. However, if one creates a default constructed iterator_range, then one can still call all its member functions. Thismeans that the iterator_range will still be usable in many contexts even though the iterators underneath are not.

Synopsis

namespace boost{

templateclass iterator_range{

public:// Forward Range types

typedef... value_type;

typedef... difference_type;typedef... size_type;typedef ForwardTraversalIterator iterator;

typedef ForwardTraversalIterator const_iterator;

public:// construction, assignment

template

iterator_range( ForwardTraversalIterator2 Begin, ForwardTraversalIterator2 End );template

iterator_range( ForwardRange& r );template

iterator_range(const ForwardRange& r );template

iterator_range&operator=( ForwardRange& r );template

iterator_range&operator=(const ForwardRange& r );public:// Forward Range functions iterator begin()const; iterator end()const; size_type size()const;

bool empty()const;

public:// convenience

operator unspecified_bool_type()const;

bool equal(const iterator_range&)const;

value_type& front()const; value_type& back()const;

// for Random Access Range only:

19

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

value_type&operator[]( size_type at )const;

};

// stream output

template std::basic_ostream&

operator<<( std::basic_ostream& Os,

const iterator_range& r );

// comparison

templatebooloperator==(const iterator_range& l,

const iterator_range& r );template

booloperator==(const iterator_range& l,

const ForwardRange& r );templatebooloperator==(const ForwardRange& l,

const iterator_range& r );templatebooloperator!=(const iterator_range& l,

const iterator_range& r );template

booloperator!=(const iterator_range& l,

const ForwardRange& r );templatebooloperator!=(const ForwardRange& l,

const iterator_range& r );templatebooloperator<(const iterator_range& l,

const iterator_range& r );template

booloperator<(const iterator_range& l,

const ForwardRange& r );templatebooloperator<(const ForwardRange& l,

const iterator_range& r );// external construction

template iterator_range< ForwardTraversalIterator >

make_iterator_range( ForwardTraversalIterator Begin, ForwardTraversalIterator End );template

iterator_range::type > make_iterator_range( ForwardRange& r );

template

iterator_range::type > make_iterator_range(const ForwardRange& r );

template

iterator_range::type > make_iterator_range( Range& r,

20

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

typename range_difference::type advance_begin,typename range_difference::type advance_end );

template

iterator_range::type > make_iterator_range(const Range& r,

typename range_difference::type advance_begin,typename range_difference::type advance_end );// convenience

template Sequence copy_range(const ForwardRange& r );}// namespace 'boost'

If an instance of iterator_range is constructed by a client with two iterators, the client must ensure that the two iterators delimita valid closed-open range [begin,end).

It is worth noticing that the templated constructors and assignment operators allow conversion from iterator_rangeto iterator_range. Similarly, since the comparison operators have two template arguments, we can compareranges whenever the iterators are comparable; for example when we are dealing with const and non-const iterators from the samecontainer.

Details member functions

operator unspecified_bool_type() const;

Returns!empty();

bool equal( iterator_range& r ) const;

Returnsbegin() == r.begin() && end() == r.end();

Details functions

bool operator==( const ForwardRange1& l, const ForwardRange2& r );

Returnssize(l) != size(r) ? false : std::equal( begin(l), end(l), begin(r) );

bool operator!=( const ForwardRange1& l, const ForwardRange2& r );

Returns!( l == r );

bool operator<( const ForwardRange1& l, const ForwardRange2& r );

Returnsstd::lexicographical_compare( begin(l), end(l), begin(r), end(r) );

iterator_range make_iterator_range( Range& r,

typename range_difference::type advance_begin,typename range_difference::type advance_end );

Effects:

21

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

iterator new_begin = begin( r ),iterator new_end = end( r );

std::advance( new_begin, advance_begin );std::advance( new_end, advance_end );

return make_iterator_range( new_begin, new_end );Sequence copy_range( const ForwardRange& r );

ReturnsSequence( begin(r), end(r) );

Class sub_range

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

22

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Synopsis

namespace boost{

template

class sub_range :public iterator_range::type >{

public:

typedeftypename range_result_iterator::type iterator;

typedeftypename range_const_iterator::type const_iterator;public:// construction, assignment

template

sub_range( ForwardTraversalIterator Begin, ForwardTraversalIterator End );template

sub_range( ForwardRange2& r );template

sub_range(const Range2& r );

template

sub_range&operator=( ForwardRange2& r );template

sub_range&operator=(const ForwardRange2& r );public:// Forward Range functions iterator begin();

const_iterator begin()const; iterator end();

const_iterator end()const;

public:// convenience

value_type& front();

const value_type& front()const;

value_type& back();

const value_type& back()const;// for Random Access Range only:

value_type&operator[]( size_type at );

const value_type&operator[]( size_type at )const;

public:

// 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. Theresult is an iterator_range, that delimits the match. We need to store the result from this algorithm. Here is an example of how wecan do it with and without sub_range

23

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

std::string str(\"hello\");

iterator_range ir = find_first( str,\"ll\");sub_range sub = find_first( str,\"ll\");

Terminology and style guidelines

The use of a consistent terminology is as important for Ranges and range-based algorithms as it is for iterators and iterator-basedalgorithms. If a conventional set of names are adopted, we can avoid misunderstandings and write generic function prototypes thatare self-documenting.

Since ranges are characterized by a specific underlying iterator type, we get a type of range for each type of iterator. Hence we canspeak of the following types of ranges:•Value access category:•Readable Range•Writeable Range•Swappable Range•Lvalue Range•Traversal category:•Single Pass Range•Forward Range•Bidirectional Range•Random Access Range

Notice how we have used the categories from the new style iterators.

Notice that an iterator (and therefore an range) has one traversal property and one or more properties from the value access category.So in reality we will mostly talk about mixtures such as•Random Access Readable Writeable Range•Forward Lvalue Range

By convention, we should always specify the traversal property first as done above. This seems reasonable since there will only beone traversal property, but perhaps many value access properties.

It might, however, be reasonable to specify only one category if the other category does not matter. For example, the iterator_rangecan be constructed from a Forward Range. This means that we do not care about what value access properties the Range has. Similarly,a Readable Range will be one that has the lowest possible traversal property (Single Pass).

As another example, consider how we specify the interface of std::sort(). Algorithms are usually more cumbersome to specifythe interface of since both traversal and value access properties must be exactly defined. The iterator-based version looks like this:

templatevoid sort( RandomAccessTraversalReadableWritableIterator first, RandomAccessTraversalReadableWritableIterator last );

For ranges the interface becomes

24

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

templatevoid sort( RandomAccessReadableWritableRange& r );

Library Headers

HeaderIncludeseverythingevery metafunctionevery functionrange_valuerange_iteratorrange_const_iteratorRelated Concept---Single Pass RangeSingle Pass RangeSingle Pass RangeForward RangeForward Range-Bidirectional Range_bidirectionalrange_-Single Pass RangeSingle Pass RangeSingle Pass RangeForward RangeBidirectional RangeBidirectional Range---range_differencerange_sizerange_result_iteratorrange_reverse_iteratorrange_const_reverse_iteratorrange_reverse_result_iteratorbegin and const_beginend and const_endemptysizerbegin and const_rbeginrend and const_renditerator_rangesub_rangeconcept checks25

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Examples

Some examples are given in the accompanying test files:

•string.cpp

shows how to implement a container version of std::find() that works with char[],wchar_t[],char*,wchar_t*.

Warning: support for null-terminated strings is deprecated and will disappear in the next Boost release(1.34).

•algorithm_example.cpp

shows the replace example from the introduction.•iterator_range.cpp•sub_range.cpp•iterator_pair.cpp•reversible_range.cpp•std_container.cpp•array.cpp

Portability

A huge effort has been made to port the library to as many compilers as possible.

Full support for built-in arrays require that the compiler supports class template partial specialization. For non-conforming compilersthere might be a chance that it works anyway thanks to workarounds in the type traits library. Visual C++ 6/7.0 has a limited supportfor arrays: as long as the arrays are of built-in type it should work.

Notice also that some compilers cannot do function template ordering properly. In that case one must rely of range_result_iter-ator and a single function definition instead of overloaded versions for const and non-const arguments. So if one cares about oldcompilers, one should not pass rvalues to the functions.For maximum portability you should follow these guidelines:1.do not use built-in arrays,

2.do not pass rvalues to begin(), end() and iterator_range Range constructors and assignment operators,

3.use const_begin() and const_end() whenever your code by intention is read-only; this will also solve most rvalue problems,4.do not rely on ADL:

•if you overload functions, include that header before the headers in this library,•put all overloads in namespace boost.

FAQ

1. Why is there no difference between range_iterator::type and range_const_iterator::type forstd::pair?

In general it is not possible nor desirable to find a corresponding const_iterator. When it is possible to comeup with one, the client might choose to construct a std::pair object.

26

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

Boost.Range Documentation

Note that an iterator_range is somewhat more convenient than a pair and that a sub_range does propagateconst-ness.

2. Why is there not supplied more types or more functions?

The library has been kept small because its current interface will serve most purposes. If and when a genuine needarises for more functionality, it can be implemented.

3. How should I implement generic algorithms for ranges?

One should always start with a generic algorithm that takes two iterators (or more) as input. Then use Boost.Rangeto build handier versions on top of the iterator based algorithm. Please notice that once the range version of thealgorithm is done, it makes sense not to expose the iterator version in the public interface.

4. Why is there no Incrementable Range concept?

Even though we speak of incrementable iterators, it would not make much sense for ranges; for example, we cannotdetermine the size and emptiness of a range since we cannot even compare its iterators.

Note also that incrementable iterators are derived from output iterators and so there exist no output range.

History and Acknowledgement

The library have been under way for a long time. Dietmar Kühl originally intended to submit an array_traits class templatewhich had most of the functionality present now, but only for arrays and standard containers.

Meanwhile work on algorithms for containers in various contexts showed the need for handling pairs of iterators, and string librariesneeded special treatment of character arrays. In the end it made sense to formalize the minimal requirements of these similar concepts.And the results are the Range concepts found in this library.

The term Range was adopted because of paragraph 24.1/7 from the C++ standard:

Most of the library's algorithmic templates that operate on data structures have interfaces that use ranges. A range is a pair of iteratorsthat designate the beginning and end of the computation. A range [i, i) is an empty range; in general, a range [i, j) refers to the elementsin the data structure starting with the one pointed to by i and up to but not including the one pointed to by j. Range [i, j) is valid ifand only if j is reachable from i. The result of the application of functions in the library to invalid ranges is undefined.Special thanks goes to

•Pavol Droba for help with documentation and implementation•Pavel Vozenilek for help with porting the library

•Jonathan Turkanis and John Torjo for help with documentation•Hartmut Kaiser for being review manager

•Jonathan Turkanis for porting the lib (as far sa possible) to vc6 and vc7.The concept checks and their documentation was provided by Daniel Walker.

27

XML to PDFby RenderX XEP XSL-FO Formatter, visit us at http://www.renderx.com/

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- stra.cn 版权所有

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务