beautypg.com

Copy one sequence into another sequence, Copy one sequence into another, Sequence – HP Integrity NonStop H-Series User Manual

Page 145

background image

vector::iterator & seven =
find(iVec.begin(), iVec.end(), 7);
fill (iVec.begin(), seven, 0);
}

In example 1, an array of character values is declared. The fill() algorithm is invoked to initialize
each location in this array with a null character value. The first 10 positions are then replaced with
the character 'x' by using the algorithm fill_n(). Note that the fill() algorithm requires both starting
and past-end iterators as arguments, whereas the fill_n() algorithm uses a starting iterator and a
count.

Example 2 illustrates how, by using an insert iterator (see

Chapter 2:

Insert Iterators

), the fill_n()

algorithm can be used to initialize a variable length container, such as a list. In this case the list
initially contains five elements, all holding the text "nothing". The call on fill_n() then inserts ten
instances of the string "empty". The resulting list contains fifteen elements.

The third and fourth examples illustrate how fill() can be used to change the values in an existing
container. In the third example each of the fifteen elements in the list created in example 2 is
replaced by the string "full".

Example 4 overwrites only a portion of a list. Using the algorithm generate and the function object
iotaGen, which we will describe in the next section, a vector is initialized to the values 1 2 3 ... 10.
The find() algorithm (

Chapter 13:

Searching Operations

) is then used to locate the position of the

element 7, saving the location in an iterator appropriate for the

vector

data type. The fill() call then

replaces all values up to, but not including, the 7 entry with the value 0. The resulting vector has six
zero fields, followed by the values 7, 8, 9 and 10.

The fill() and fill_n() algorithm can be used with all the container classes contained in the standard
library, although insert iterators must be used with ordered containers, such as a

set

.

Copy One Sequence Into Another Sequence

Appending Several Copies

The algorithms copy() and copy_backward() are versatile functions that can be used for a number of
different purposes, and are probably the most commonly executed algorithms in the standard
library. The declarations for these algorithms are as follows:

OutputIterator copy (InputIterator first, InputIterator last,
OutputIterator result);

BidirectionalIterator copy_backward
(BidirectionalIterator first, BidirectionalIterator last,
BidirectionalIterator result);

Uses of the copy algorithm include:

Duplicating an entire sequence by copying into a new sequence

Creating subsequences of an existing sequence

This manual is related to the following products: