An inserter iterator is an iterator that can add new elements to the sequence containers
vector < T > ,
deque < T > , and
list < T > . There are three templates that create inserter iterators:
- back_insert_iterator < T > — inserts elements at the end of a container of type T . The container
must provide the push_back() function for this to work.
- front_insert_iterator < T > — inserts elements at the beginning of a container of type T .
This depends on push_front() being available for the container.
- insert_iterator < T > — inserts elements starting at a specifi ed position within a container
of type T . This requires that the container has an insert() function that accepts an iterator
as the fi rst argument, and an item to be inserted as the second argument.
The constructors for the fi rst two types of inserter iterators expect a single argument specifying the
container in which elements are to be inserted. For example:
list < int > numbers;
front_insert_iterator < list < int > > iter(numbers);
*iter = 99; // front_inserter(numbers) = 99;
The constructor for an insert_iterator < T > iterator requires two arguments:
insert_iterator < vector < int > > iter_anywhere(numbers, numbers.begin());
The second argument to the constructor is an iterator specifying where data is to be inserted — the
start of the sequence, in this instance. You can use this iterator in exactly the same way as
the previous one. Here ’ s how you could insert a series of values into a vector container using this iterator:
for(int i = 0 ; i < 100 ; i++)*iter_anywhere = i + 1;
This loop inserts the values from 1 to 100 in the numbers container at the beginning. After
executing this, the fi rst 100 elements will be 100 , 99 , and so on, through to 1 .
You could also use the
inserter() function to achieve the same result:
for(int i = 0 ; i < 100 ; i++)
inserter(numbers, numbers.begin()) = i + 1;
The first argument is the container, and the second is an iterator identifying the
position where data is to be inserted. The inserter iterators can be used in conjunction with
the
copy() algorithm in a particularly useful way. Here ’ s how you could read values from cin and
transfer them to a list < T > container:
list < double > values;
cout < < "Enter a series of values separated by spaces"
< < " followed by Ctrl+Z or a letter to end:" < < endl;
istream_iterator < double > input(cin), input_end;
copy(input, input_end, back_inserter < list < double > > (values));