BDE 4.14.0 Production release
|
Provides an output iterator for a client-supplied functor.
This component provides an iterator template mechanism, bdlb::FunctionOutputIterator
, that adapts a client supplied functor (or function pointer) to a C++ compliant output iterator. This component allows clients to create custom output iterators easily.
A bdlb::FunctionOutputIterator
instance's template parameter type FUNCTION
must be a functor (or function) that can be called as if it has the following signature:
where TYPE
is the type of the object that will be assigned (by clients) to the dereferenced iterator. For example:
Notice that assigning 5 to the dereferenced output iterator invokes the function with the value 5.
The provided output iterator has the following attributes:
*it = value
is equivalent to function(value)
.This section illustrates intended use of this component.
Suppose we want use a provided function foo
, that prints integers in some predefined format, to print each unique element of an array. Instead of manually writing a loop and checking for duplicate elements, we would like to use a standard algorithm such as unique_copy . However, unique_copy takes in an output iterator instead of a free function. We can use bdlb::FunctionOutputIterator
to adapt foo
into an output iterator that is acceptable by unique_copy .
First, we define the type Function
and a function of that type foo
:
Then, we define a data sequence to process:
Next, we use bdlb::FunctionOutputIterator
to wrap foo
for use in the algorithm bsl::unqiue_copy
:
Notice, that each time bsl::unique_copy
copies an element from the supplied range and assigns it to the output iterator, the function foo
is called for the element.
Finally, the resulting console output:
The following example demonstrates using a bdlb::FunctionOutputIterator
with a user defined functor object. Consider the Accumulator
class for accumulating integer values into a total. We want to adapt Accumulator
for use with the algorithm bsl::unique_copy
.
First, we define an Accumulator
class that will total the values supplied to the increment
method:
Next, we define a functor, AccumulatorFunctor
, that adapts Accumulator
to a function object:
Then, we define data sequence to process:
Next, we create a bdlb::FunctionOutputIterator
for AccumulatorFunctor
and supply it to the bsl::unique_copy
algorithm to accumulate a sequence of values:
Finally, we observe that accumulator
holds the accumulated total of unique values in array
: