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 type | definition |
---|---|
conainer_type | Container |
iterator_category | output_iterator_tag |
value_type | void |
difference_type | void |
pointer | void |
reference | void |
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
Name | Description |
---|---|
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
Name | Example |
---|---|
reference operator*() | No Operation. |
| 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