Quick Links:

bal | bbl | bdl | bsl

Namespaces

Component bsltf_inputiterator
[Package bsltf]

Provide a pure input iterator capable of traversing a range. More...

Namespaces

namespace  bsltf

Detailed Description

Outline
Purpose:
Provide a pure input iterator capable of traversing a range.
Classes:
bsltf::InputIterator empty input iterator template
Description:
This components provides a value-semantic class, bsltf::InputIterator, that defines an input iterator that supports the following operations:
  • Obj& operator++()
  • Obj operator++(int)
  • pointer operator->() const
  • reference& operator*() const
The iterator is initializable with either a pointer into a range, or a non-pointer iterator over a contiguous range.
This iterator type is typically used to check algorithms for compatibility with input iterators. The goal is to make sure that their code is able to compile and work even with the most restrictive input iterator.
Usage:
This section illustrates intended use of this component.
Example 1: Basic Use of bsltf::InputIterator:
In the following example we use a bsltf::InputIterator to test that an aggregation function compiles and works when instantiated with a pure input iterator.
First, we define a function sum that accepts two input iterators and returns the sum of all elements in range specified by them:
  template <class IN_ITER>
  double sum(IN_ITER first, IN_ITER last)
      // Return the sum of the 'double's in the specified range
      // '[ first, last )'.
  {
      double total = 0;
      while (first != last) {
          total += *first++;
      }
      return total;
  }
Then, in main, we define an array of doubles and define InputIterators pointing to the beginning and ending of it, initializing the iterators with pointers:
  static double myArray[] = { 2.5, 3, 5, 7, 11.5, 5 };
  enum { k_MY_ARRAY_LEN = sizeof myArray / sizeof *myArray };

  typedef bsltf::InputIterator<const double> Iter;

  Iter begin(myArray + 0), end(myArray + k_MY_ARRAY_LEN);
Next, we call sum with the two iterators, and observe that its yields the expected result, and because it compiles, we know that sum did not attempt any operations on the iterators other than those defined for the most basic input iterator:
  const double x = sum(begin, end);
  assert(34.0 == x);
Then, we illustrate that we can just make begin and end iterators from the array directly with the begin and end class methods of the InputIteratorUtil class.
  typedef bsltf::InputIteratorUtil Util;

  const double y = sum(Util::begin(myArray), Util::end(myArray));
  assert(34.0 == y);
Now, we make an std::vector containing the elements of myArray:
  const std::vector<double> v(myArray + 0, myArray + k_MY_ARRAY_LEN);
Finally, we call sum using, again, the begin and end class methods to create iterators for it directly from our vector:
  const double z = sum(Util::begin(v), Util::end(v));
  assert(34.0 == z);