Overview
The STL algorithms usually overwrite elements of the range passed to them as parameters. Instead, sometimes it's useful to prepend new elements to the range. front_insert_iterator designed exactly to do it.
Details
A front_insert_iterator is a special output iterator which can be generated for containers that support push_front() 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 front_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 front_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 front_insert_iterator does nothing.
This can be clearly seen in the example below.
list<int> v{3,4}; front_insert_iterator<list<int> > frontiter ( v );//v:{2,3,4} *frontiter = 2;//v:{1,2,3,4} frontiter = 1;
Functionality
Constructors
Name | Description |
---|---|
front_insert_iterator(Container& c) | Initializes the underlying pointer to the container to addressof(c). Example: list<int> v{1, 2, 3, 4, 5}; front_insert_iterator<list<int>> frontiter (v); |
Overloaded operators
Name | Example |
---|---|
reference operator*() | No Operation. |
| No Operation. |
pointer operator=() | Prepends new element. Example: list<int> v{3,4}; front_insert_iterator<list<int> > frontiter ( v );//v:{2,3,4} *frontiter = 2; |
front_inserter
An utility function to create a front_insert_iterator from a container that supports push_front() method such as deque, list.
Syntax
The syntax is as below. Template parameter Container represents the container for which
front_inserter_iterator is created. Container represents must support push_front() function as in deque and list.
template < class Container >front_insert_iterator<Container > front_inserter( Container& c );
The following example shows its usage.
list<int> v{1,2,3,4}, v2; //same as //for_each(rbegin(v),rend(v),[&v2](int i){push_front(i);}); //v2:{1,2,3,4} copy (v.rbegin(),v.rend(),front_inserter(v2));
No comments:
Post a Comment