beautypg.com

Adjacent differences – HP Integrity NonStop H-Series User Manual

Page 175

background image

// output partial products
partial_sum (aVec.begin(), aVec.end(),
ostream_iterator (cout, " "),
times() );
}

Adjacent Differences

An adjacent difference of a sequence is a new sequence formed by replacing every element with
the difference between the element and the immediately preceding element. The first value in the
new sequence remains unchanged. For example, a sequence such as (1, 3, 2, 4, 5) is transformed
into (1, 3-1, 2-3, 4-2, 5-4), and in this manner becomes the sequence (1, 2, -1, 2, 1).

As with the algorithm partial_sum(), the term "difference" is not necessarily accurate, as an
arbitrary binary function can be employed. The adjacent sums for this sequence are (1, 4, 5, 6, 9),
for example. The adjacent difference algorithm has the following declaration:

OutputIterator adjacent_difference (InputIterator first,
InputIterator last, OutputIterator result [, BinaryFunction ]);

By using the same iterator as both input and output iterator, the adjacent difference operation can
be performed in place.

void adjacent_difference_example ()
// illustrate the use of the adjacent difference algorithm
{
// generate values 1 to 5
vector aVec(5);
generate (aVec.begin(), aVec.end(), iotaGen(1));

// output adjacent differences
adjacent_difference (aVec.begin(), aVec.end(),
ostream_iterator (cout, " ")), cout << endl;

// output adjacent sums
adjacent_difference (aVec.begin(), aVec.end(),
ostream_iterator (cout, " "),
plus() );
}

This manual is related to the following products: