function template
<iterator>

std::front_inserter

template <class Container>
  front_insert_iterator<Container> front_inserter (Container& x);
Constructs front insert iterator
Constructs a front-insert iterator that inserts new elements at the beginning of x.

A front-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 the beginning of the container.

The type of x needs to have a push_front member function (such as the standard containers deque and list).

Using the assignment operator on the returned iterator (either dereferenced or not), causes the container to expand by one element, which is initialized to the value assigned.

The returned iterator supports all other typical operations of output iterators but have no effect: all values assigned are inserted at the end of the container.

Parameters

x
Container on which the iterator will insert new elements.
Container should be a container class with member push_front defined.

Return value

A front_insert_iterator that inserts elements at the end of container x.

Example

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

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

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

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

  return 0;
}


Output:

50 40 30 20 10 1 2 3 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

Other than if x somehow throws while applying the unary operator& to it, this function never throws exceptions (no-throw guarantee).

See also