Insert iterators – HP Integrity NonStop H-Series User Manual
Page 34
![background image](/manuals/396950/34/background.png)
Click on the banner to return to the user guide home page.
©Copyright 1996 Rogue Wave Software
Insert Iterators
Assignment to the dereferenced value of an output iterator is normally used to overwrite the
contents of an existing location. For example, the following invocation of the function copy()
transfers values from one vector to another, although the space for the second vector was already set
aside (and even initialized) by the declaration statement:
vector
vector
...
copy (a.begin(), a.end(), b.begin());
Even structures such as lists can be overwritten in this fashion. The following assumes that the list
named c has at least ten elements. The initial ten locations in the list will be replaced by the contents
of the vector a.
list
...
copy (a.begin(), a.end(), c.begin());
With structures such as lists and sets, which are dynamically enlarged as new elements are added, it
is frequently more appropriate to insert new values into the structure, rather than to overwrite
existing locations. A type of adaptor called an insert iterator allows us to use algorithms such as
copy() to insert into the associated container, rather than overwrite elements in the container. The
output operations of the iterator are changed into insertions into the associated container. The
following, for example, inserts the values of the vector a into an initially empty list:
list
copy (a.begin(), a.end(), front_inserter(d));
There are three forms of insert iterators, all of which can be used to change a copy operation into an
insert operation. The iterator generated using front_inserter, shown above, inserts values into the
front of the container. The iterator generated by back_inserter places elements into the back of the
container. Both forms can be used with
list
s and
deque
s, but not with
set
s or
map
s. back_inserter,
but not front_inserter, can be used with
vector
.
The third, and most general form, is inserter, which takes two arguments; a container and an iterator
within the container. This form copies elements into the specified location in the container. (For a
list, this means elements are copied immediately before the specified location). This form can be
used with all the structures for which the previous two forms work, as well as with sets and maps.