Home > Articles

  • Print
  • + Share This
This chapter is from the book

34.4 Ranges

We've seen that there are two issues in the enumeration of ranges and the use of functors. First, we have a desire to avoid the general, though not universal, repeated stipulation of the begin() and end() methods for sequence types. Second, we have a need to avoid writing overly specific "write-once, use nowhere else" functors.

In a discussion with my friend John Torjo,7 we discovered that we've had similar disenchantments with these issues, and wanted a better solution. We came up with the Range concept. Naturally, he and I see the issue slightly differently;8 the concept definition and component implementations presented here primarily reflect my view.

34.4.1 The Range Concept

The range concept is quite simple.


Definition: A Range represents a bounded collection of elements, which may be accessed in an incremental fashion. It encapsulates a logical range—that is, a beginning and end point, along with rules for how to walk through it (move from the beginning to the end point)—and embodies a single entity with which client code may access the values contained within the range.

Sounds almost too simple to be meaningful, doesn't it? Well, the salient part of the definition is that it's a single entity. The canonical form of use is:

for(R r = . . .; r; ++r)

or, if you don't go for all that operator overloading:

for(R r = . . .; r.is_open(); r.advance())

There's noticeable brevity of form, which is part the raison d'être of ranges. A range has the characteristics shown in Table 34.2.

Table 34.2 Characteristics of a notional range.







*r or r.current()

Returns the value of represented at the current position

r has not reached its end condition

r is unchanged


++r or r.advance()

Advances r's current position

r has not reached its end condition

r is dereference- able or has reached its end condition


r or r.is_open()

Evaluates to true if r has reached its end condition, false otherwise


r is unchanged

Let's look at a couple of ranges in action:

// A range over a sequence
glob_sequence gs("/usr/include/", "impcpp*");
for(sequence_range<glob_sequence> r(gs); r; ++r)
  puts(*r); // Print the matched file entry to stdout
// A "notional range"
for(integral_range<int> r(10, 20, 2); r; ++r)
  cout << *r << endl; // Print int value at current point

There's no way any pointer can fit the range syntax9 so we don't have to worry about catering for any fundamental types; this provides us with a lot of extra flexibility in the implementation. In other words, we can rely on all range instances being of class types, and therefore we can rely on the presence or absence of class type characteristics in order to specialize behavior for the algorithms that operate on ranges (see section 34.4.4).

The way this works is similar to the implementation of algorithms that manipulate Iterators [Aust1999], only simpler. My implementation of ranges simply relies on the specific range types deriving from the appropriate range type tag structure:

struct simple_range_tag
struct iterable_range_tag
  : public simple_range_tag

We'll see how these are used in the next sections.

34.4.2 Notional Range

Sometimes you don't have a concrete range, that is, one defined by two iterators; rather you have a notional range. It might be the odd numbers between 1 and 99. In this simple case you know that the number of odd numbers is 49 (1–97 inclusive), and so what you might do in classic STL is as shown in Listing 34.8:

Listing 34.8

struct next_odd_number
  next_odd_number(int first)
    : m_current(first - 2)
  int operator ()()
    return ++++m_current; // Nasty, but it fits on one line ;/
  int m_current;
std::vector<int>  ints(49);
std::generate(ints.begin(), ints.end(), next_odd_number(1));

Books on STL tend to show such things as perfectly reasonable examples of STL best practice. That may indeed be the case, but to me it's a whole lot of pain. First, we have the creation of a functor that will probably not be used elsewhere.

Second, and more significantly, the technique works by treating the functor as a passive producer whose actions are directed by the standard library algorithm generate(), whose bounds are, in turn, defined by the vector. This is very important, because it means that we need to know the number of results that will be created beforehand, in order to create spaces for them in the vector. Hence, we need a deep appreciation of how the producer—the functor—works. In this simple case, that is relatively straightforward—although I must confess I did get it wrong when preparing the test program! But imagine if we were computing the members of the Fibonacci series up to a user-supplied maximum value. It would be impossible to anticipate the number of steps in such a range other than by enumerating it to completion, which would be a drag, not to mention inefficient.

What we want in such cases is for the producer to drive the process, in accordance with the criteria stipulated by the code's author. Time to crank out my favorite example range, the integral_range template, whose simplified definition is shown in Listing 34.9:

Listing 34.9

template <typename T>
class integral_range
  : public simple_range_tag
  typedef simple_range_tag  range_tag_type;
  typedef T                 value_type;
// Construction
  integral_range( value_type first, value_type last
                , value_type increment = +1)
    // Ensure that the parameterising type is integral
    STATIC_ASSERT(0 != is_integral_type<T>::value);
// Enumeration
  operator "safe bool"() const; // See Chapter 24
  value_type operator *() const;
  class_type &operator ++();
// Members
  . . .

The integral_range performs enumeration over its logical range via member variables of the given integral type, T.

We can now rewrite the instantiation of the vector with odd numbers as follows:

std::vector<int>  ints;
ints.reserve(49); // No problem if this is wrong.
r_copy(integral_range<int>(1, 99, 2), std::back_inserter(ints));

Note that the call to reserve() is an optimization and can be omitted without causing any change to the correctness of the code. r_copy() is a range algorithm (see section 34.4.3) that has the same semantics as the standard library algorithm copy() [Muss2001]. Now the producer, the instance of integral_range<int>, drives the process, which is as it should be. We could easily substitute a Fibonacci_range here, and the code would work correctly and efficiently, which cannot be said for the STL version.

34.4.3 Iterable Range

The Iterable range is an extension of the Notional range, with the additional provision of begin(), end() and range() methods, allowing it to be fully compatible with standard STL algorithms and usage (see section 34.4.4).

Iterable ranges usually maintain internal iterators reflecting the current and past-the-end condition positions, and return these via the begin() and end() methods. The range() method is provided to allow a given range to be cloned in its current enumeration state, although this is subject to the restrictions on copying iterators if the range's underlying iterators are of the Input or Output Iterator concepts [Aust1999, Muss2001]: only the Forward and "higher" models [Aust1999, Muss2001] support the ability to pass through a given range more than once.

It is possible to write iterable range classes, but the common idiom is to use an adaptor. In my implementation of the Range concept, I have two adaptors, the sequence_range and iterator_range template classes. Obviously the sequence_range adapts STL Sequences, and the iterator_range adapts STL Iterators.

Given a sequence type, we can adapt it to a range by passing the sequence instance to the constructor of an appropriate instantiation of sequence_range, as in:

std::deque<std::string> d = . . . ;

sequence_range< std::deque<std::string> > r(d);
for(; r; ++r)
  . . . // Use *r 

Similarly, an iterator_range is constructed from a pair of iterators, as in:

vector<int> v = . . . ;
for(iterator_range<vector<int>::iterator> r(v.begin(), v.end());
    r; ++r)
  . . . // Use *r 

Iterable ranges at first glance appear to be nothing more than a syntactic convenience for reducing the clutter of unwanted variables when processing iterator ranges in unrolled loops. I must confess that this in itself represents a big attraction to draw for me, but the concept offers much more as we'll see in the next couple of sections.

34.4.4 Range Algorithms and Tags

All the examples so far have shown ranges used in unrolled loops. Ranges may also be used with algorithms. That's where the separation of Notional and Iterable range concepts comes in.

Consider the standard library algorithm distance().

template <typename I>
size_t distance(I first, I last);

This algorithm returns the number of elements represented by the range [first, last). For all iterator types other than Random Access [Aust1999, Muss2001], the number is calculated by iterating first until it equals last. But the template is implemented to simply and efficiently calculate (last – first) for random access iterators. We certainly don't want to lose such efficiency gains when using algorithms with ranges.

The answer is very simple: we implement the range algorithms in terms of the standard library algorithms where possible. The range algorithm r_distance() is defined as shown in Listing 34.10:

Listing 34.10

template <typename R>
ptrdiff_t r_distance_1(R r, iterable_range_tag const &)
  return std::distance(r.begin(), r.end());
template <typename R>
ptrdiff_t r_distance_1(R r, simple_range_tag const &)
  ptrdiff_t d = 0;
  for(; r; ++r, ++d)
  return d;
template <typename R>
inline ptrdiff_t r_distance(R r)
  return r_distance_1(r, r);

r_distance() is implemented in terms of r_distance_1(),10 which has two definitions: one for the iterable ranges that defers to a standard library algorithm, and one for notional ranges that carries out the enumeration manually. The two overloads of r_distance_1() are distinguished by their second parameter, which discriminate on whether the ranges as simple or iterable.

We use run time polymorphism (inheritance) to select the compile-time polymorphism (template type resolution), so we need to pass the range to r_distance_1() in two parameters, to preserve the actual type in the first parameter while at the same type discriminating the overload in the second. Since compilers can make mincemeat of such simple things, there're no concerns regarding inefficiency, and the mechanism ably suffices. We saw in section 34.4.2 that the integral_range template inherited from simple_range_tag. Iterable ranges inherit from iterable_range_tag. Hence the implementations of all range algorithms unambiguously select the most suitable implementation.

We can now come back and address the algorithm name problem (see section 34.2.2). Since we're clearly distinguishing between iterator-pair ranges and instances of a range class, we're never going to need the same name to facilitate generalized programming because the former ranges come as two parameters and the latter as one. Therefore, we can avoid all the namespace tribulations and just use algorithms with an r_ prefix.

34.4.5 Filters

Another powerful aspect of the Range concept abstraction is that of filters. This aspect of ranges is only just developing, but is already promising great benefits. I'll illustrate with a simple filter divisible, which we'll apply to our integral_range.

Listing 34.11

template <typename R>
struct divisible
	: public R::range_tag_type
  typedef R                       filtered_range_type;
  typedef typename R::value_type  value_type;
  divisible(filtered_range_type r, value_type div)
    : m_r(r)
    , m_div(div)
    assert(div > 0);
    for(; m_r && 0 != (*m_r % m_div); ++m_r)
  operator "safe bool"() const; // See Chapter 24
    . . . // implemented in terms of m_r's op safe bool
  value_type operator *() const
    return *m_r;
  class_type &operator ++()
    for(; m_r && 0 != (*++m_r % m_div); )
    return *this;
  filtered_range_type m_r;
  value_type          m_div;

When combined with integral_range, we can filter out all the odd numbers in a given range to only those that are wholly divisible by three, as in:

std::vector<int>    ints;
integral_range<int> ir(1, 99, 2);
r_copy( divisible<integral_range<int> >(ir, 3)
      , std::back_inserter(ints));

Naturally range filters can be a lot more sophisticated than this in the real world.

34.4.6 Hypocrisy?

As someone who is against the abuse of operator overloading,11 I am certainly open to accusations of hypocrisy when it comes to the operators that ranges support. Clearly it can be argued, if one wished to be terribly uncharitable, that the unrealistic combination of operators provided by ranges is an abuse.

I can't really defend the concept in any purist sense, so I can fall back on the Imperfect Practitioner's Philosophy, and state that the fact that it works so well, and so simply, is worth the pricked conscience.

If you like the range concept, but don't want to go for the operator overloading, it is a simple matter to replace some or all of the operators with methods. The semantics and efficiency will be the same; only the syntax will be slightly heavier.

for(R r = . . .; r.is_open(); r.advance())
  . . . = r.current();
  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020