How it works...

std::back_inserter(), std::front_inserter(), and std::inserter() are all helper functions that create iterator adapters of types, std::back_insert_iterator, std::front_insert_iterator, and std::insert_iterator. These are all output iterators that append, prepend, or insert into the container for which they were constructed. Incrementing and dereferencing these iterators does not do anything. However, upon assignment, these iterators call the following methods from the container:

  • std::back_insterter_iterator calls push_back()
  • std::front_inserter_iterator calls push_front()
  • std::insert_iterator calls insert()

The following is the over-simplified implementation of std::back_inserter_iterator:

    template<class C>
class back_insert_iterator {
public:
typedef back_insert_iterator<C> T;
typedef typename C::value_type V;

explicit back_insert_iterator( C& c ) :container( &c ) { }

T& operator=( const V& val ) {
container->push_back( val );
return *this;
}

T& operator*() { return *this; }

T& operator++() { return *this; }

T& operator++( int ) { return *this; }
protected:
C* container;
};

Because of the way the assignment operator works, these iterators can only be used with some standard containers:

  • std::back_insert_iterator can be used with std::vector, std::list, std::deque, and std::basic_string.
  • std::front_insert_iterator can be used with std::list, std::forward_list, and std:deque.
  • std::insert_iterator can be used with all the standard containers.

The following example inserts three elements with the value 0 at the beginning of an std::vector:

    std::vector<int> v{ 1,2,3,4,5 };
std::fill_n(std::inserter(v, v.begin()), 3, 0);
// v={0,0,0,1,2,3,4,5}

The std::inserter() adapter takes two arguments: the container, and the iterator where an element is supposed to be inserted. Upon calling insert() on the container, the std::insert_iterator increments the iterator, so upon being assigned again, it can insert a new element into the next position. Here is how the assignment operator is implemented for this iterator adapter:

    T& operator=(const V& v)
{
iter = container->insert(iter, v);
++iter;
return (*this);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset