C++ Iterator Library - inserter


It constructs an insert iterator that inserts new elements into x in successive locations starting at the position pointed by it.


Following is the declaration for std::inserter.


template <class Container, class Iterator>
  insert_iterator<Container> inserter (Container& x, Iterator it);


x − It is a container on which the iterator will insert new elements.

Return value

It returns an insert_iterator that inserts elements into x at the position indicated by it.


If x somehow throws while applying the unary operator& to it, this function never throws exceptions.

Time complexity

constant for random-access iterators.


The following example shows the usage of std::inserter.

#include <iostream>
#include <iterator> 
#include <list>
#include <algorithm>

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

   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;

Let us compile and run the above program, this will produce the following result −

foo contains: 1 2 3 5 10 15 20 25 4 5