beautypg.com

In-place transformations, Reverse elements in a sequence, Chapter 13 – HP Integrity NonStop H-Series User Manual

Page 157

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

In-Place Transformations

Obtaining the Source

The next category of algorithms in the standard library that we examine are those used to modify
and transform sequences without moving them from their original storage locations. A few of these
routines, such as replace(), include a copy version as well as the original in-place transformation
algorithms. For the others, should it be necessary to preserve the original, a copy of the sequence
should be created before the transformations are applied. For example, the following illustrates how
one can place the reversal of one vector into another newly allocated vector.

vector newVec(aVec.size());
copy (aVec.begin(), aVec.end(), newVec.begin()); // first copy
reverse (newVec.begin(), newVec.end()); // then reverse

Many of the algorithms described as sequence generating operations, such as transform()
(

Transform One or Two Sequences

), or partial_sum(), can also be used to modify a value in place

by simply using the same iterator as both input and output specification.

Reverse Elements in a Sequence

The algorithm reverse() reverses the elements in a sequence, so that the last element becomes the
new first, and the first element the new last. The arguments are assumed to be bidirectional iterators,
and no value is returned.

void reverse (BidirectionalIterator first,
BidirectionalIterator last);

The example program illustrates two uses of this algorithm. In the first, an array of characters
values is reversed. The algorithm reverse() can also be used with list values, as shown in the second
example. In this example, a list is initialized with the values 2 to 11 in increasing order. (This is
accomplished using the iotaGen function object introduced in

Chapter 3:

Functions Objects

). The list

is then reversed, which results in the list holding the values 11 to 2 in decreasing order. Note,
however, that the list data structure also provides its own reverse() member function.

void reverse_example ()
// illustrate the use of the reverse algorithm
{
// example 1, reversing a string
char * text = "Rats live on no evil star";

This manual is related to the following products: