function template
<iterator>

std::inserter

template <class Container, class Iterator>  insert_iterator<Container> inserter (Container& x, Iterator it);
template <class Container>  insert_iterator<Container> inserter (Container& x, typename Container::iterator it);
Construct insert iterator
Constructs an insert iterator that inserts new elements into x in successive locations starting at the position pointed by it.

An insert interator is a special type of output iterator designed to allow algorithms that usually overwrite elements (such as copy) to instead insert new elements automatically at a specific position in the container.

The type of x needs to have an insert member function (such as most standard containers).

Using the assignment operator on the returned iterator (either dereferenced or not), causes insert to be called on the container, attempting to insert one element at the current insert position with the value assigned. This effectively expands the container by one element when successful.

The returned iterator supports all other typical operations of output iterators but have no effect: all values assigned are inserted at the current insert position - which is it after this function is called, and is incremented after each new insertion caused by an assignment to the iterator.

Parameters

x
Container on which the iterator will insert new elements.
Container should be a container class with member insert defined.
it
Iterator pointing to the insertion point.
This shall be a mutable iterator (not a const iterator).

Return value

An insert_iterator that inserts elements into x at the position indicated by it.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// inserter example
#include <iostream>     // std::cout
#include <iterator>     // std::front_inserter
#include <list>         // std::list
#include <algorithm>    // std::copy

int main () {
  std::list<int> foo,bar;
  for (int i=1; i<=5; i++)
  { foo.push_back(i); bar.push_back(i*10); }

  std::list<int>::iterator it = foo.begin();
  advance (it,3);

  std::copy (bar.begin(),bar.end(),std::inserter(foo,it));

  std::cout << "foo contains:";
  for ( std::list<int>::iterator it = foo.begin(); it!= foo.end(); ++it )
	  std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

Output:

1 2 3 10 20 30 40 50 4 5


Data races

The container (x) is not accessed by the call other than to obtain a reference to it, but the returned object may be used to access or modify it.

Exception safety

Provides the same level of guarantee as dereferencing x and copying it.

See also