Thursday, October 17, 2024

insert_iterator


Overview
The STL algorithms usually overwrite elements of the range passed to them as parameters. Instead, sometimes it's useful to insert new elements to the range. insert_iterator is designed exactly to do it.

Details
A insert_iterator is a special output iterator which can be generated for containers that support insert()  method as in the standard containers  deque and list.

Syntax
The syntax is as below. Template parameter Container represents the container that is updated.
template < class Container > 
class  insert_insert_iterator;

Members
 It defines following types.
member typedefinition
conainer_typeContainer
iterator_categoryoutput_iterator_tag
value_typevoid
difference_typevoid
pointervoid
referencevoid

Operation
An insert_iterator supports three operators *, ++ and =. 
The assignment operator, used both during dereferencing or directly, causes the container to expand by one element. For example, both *i = x and i=x adds a new element.
Dereferencing operator does nothing.
Both pre and post Increments the insert_iterator does nothing.

This can be clearly seen in the example below. 
deque<int> v{3,4};
insert_iterator<deque<int> > insiter ( v, v.begin() );

//v:{1,3,4}
insiter = 1;

//v:{1,2,3,4}
*insiter = 2;

Functionality

Constructors
NameDescription
insert_iterator(Container& c,Container::iterator itr )
Initializes the underlying pointer to the container to addressof(c) and the underlying iterator to itr.

Example:
deque<int> v{3,4};
insert_iterator<deque<int> > insiter ( v, v.begin() );


Overloaded operators
NameExample
reference operator*() No Operation.
  1. insert_iterator& operator++()
  2. insert_iterator operator++(int)
No Operation.
pointer operator=() Prepends new element.

Example:
deque<int> v{3,4};
insert_iterator<deque<int> > insiter ( v, v.begin() );

//v:{1,3,4}
insiter = 1;

//v:{1,2,3,4}
*insiter = 2;


inserter
An utility function to create a insert_iterator from a container that supports insert() method such as  deque, list.

Syntax
The syntax is as below. Template parameter Container represents the container for which 
inserter _iterator is created. Container represents must support insert() function as in  deque and list.
template < class Container > 
insert_iterator<Container >  inserter( Container& c, Container::iterator i );

The following example shows its usage.
template<typename T>
T operator+ (T it, typename T::difference_type i)
{
    advance(it,i);
    return it;
}

deque<int> v{3,4}, v2{1,2,5};

//same as 
//for_each(rbegin(v),rend(v),[&v2](int i){v2.insert(begin(v2)+2,i);});
//v2:{1,2,3,4,5}
copy (v.begin(),v.end(),inserter(v2, begin(v2)+2));




No comments:

Post a Comment