C++ Iterator Library - back_inserter



Description

It constructs a back-insert iterator that inserts new elements at the end of x.

Declaration

Following is the declaration for std::back_inserter.

C++11

template <class Container>
  back_insert_iterator<Container> back_inserter (Container& x);

Parameters

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

Return value

It returns back_insert_iterator that inserts elements at the end of container x.

Exceptions

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

Time complexity

constant for random-access iterators.

Example

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

#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

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

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

   std::cout << "foo contains:";
   for ( std::vector<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 1 2 3
iterator.htm
Advertisements